Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow null default value while enforcing required validation #556

Closed
g-kduvignau opened this issue Apr 30, 2024 · 2 comments
Closed

Allow null default value while enforcing required validation #556

g-kduvignau opened this issue Apr 30, 2024 · 2 comments
Assignees
Labels
enhancement New feature or request

Comments

@g-kduvignau
Copy link

g-kduvignau commented Apr 30, 2024

Hi! 馃憢

I'm using valibot with react-hook-form, and I need one of my properties to be required but with a default value of null. When the form is submitted and the value is still null, it should not validate.

So far, I've managed this by creating a derived type from the output schema. However, I'm wondering if there's a more efficient way to handle this scenario?

I've added a simplified example of my scenario. The role selection isn't a typical input (here it's a clickable div, in my actual scenario it's a custom component).

Thank you!

import { valibotResolver } from "@hookform/resolvers/valibot";
import { Controller, useForm } from "react-hook-form";
import { nullable, object, type Output, string } from "valibot";

export const Form = () => {
  const { handleSubmit, control } = useForm<FormInput>({
    defaultValues: {
      name: "test",
      role: null,
      secondaryRole: null
    },
    resolver: valibotResolver(FormSchema)
  });

  const onSubmit = (data: FormInput) => {
    console.log(data.role!.name);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <Controller 
          control={control}
          name="role"
          render={({ field: { onChange } }) => (
            <div onClick={() => onChange({ id: "role1", name: "Role 1" })}>Select role</div>
          )}
        />
        <button type="submit">Submit</button>
      </div>
    </form>
  );
};

export const FormSchema = object({
  name: string(),
  role: object({
    id: string(),
    name: string()
  }),
  secondaryRole: nullable(
    object({
      id: string(),
      name: string()
    })
  )
});

type FormOutput = Output<typeof FormSchema>;

type FormInput = Omit<FormOutput, "role"> & {
  role: FormOutput["role"] | null;
};
@fabian-hiller
Copy link
Owner

Hi 馃憢馃徏 this will be possible soon once #502 is merged. Until then, you can use the following workaround:

import * as v from 'valibot';

const FormSchema = v.object({
  name: v.string(),
  role: v.nullable(
    v.object({
      id: v.string(),
      name: v.string(),
    }),
    { id: '', name: '' }
  ),
  secondaryRole: v.nullable(
    v.object({
      id: v.string(),
      name: v.string(),
    })
  ),
});

type FormInput = v.Input<typeof FormSchema>;
type FormOutput = v.Output<typeof FormSchema>;

@fabian-hiller fabian-hiller self-assigned this Apr 30, 2024
@fabian-hiller fabian-hiller added the enhancement New feature or request label Apr 30, 2024
@fabian-hiller
Copy link
Owner

#502 is merged 馃殌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants