I'm creating multi-step form in React and using React Hook Form and Zod for validation. To keep it simple, lets assume that I have only two steps and three fields.
Step one:
Select with two options - this field is required.
<Select placeholder='Select option' {...register("select")}>
<option value='A'>Option A</option>
<option value='B'>Option B</option>
</Select>
Step two:
Here are two fields, and its visibility is dependent on value from previous step.
{inputOneVisible && <Input placeholder='Input 1' {...register("inputOne")}/>}
{inputTwoVisible && <Input placeholder='Input 2' {...register("inputTwo")}/>}
Both of inputs have different validations, but I need to validate only one depending on the param from select. Can such validation be done if I'm using separate schemas per every step of form?
export const stepOneSchema = z.object({
options: z.string()
});
export const stepTwoSchema = z.object({
input1: z.string(),
input2: z.string()
});
Edit: I didn't mention that the steps are separate forms managed by a container components which render proper form depending on step number.
You can perform conditional validation using React-hook-form along with Zod, with or without having seperate schemas for each step
1.Update the Schema for Step 2:
export const stepTwoSchema = z.object({
inputOne: z.string().optional(),
inputTwo: z.string().optional(),
}).superRefine((data, ctx) => {
const selectedOption = ctx.parent?.select;
if (selectedOption === 'A' && !data.inputOne?.trim()) {
ctx.addIssue({
path: ['inputOne'],
message: 'Input 1 is required when Option A is selected.',
});
}
if (selectedOption === 'B' && !data.inputTwo?.trim()) {
ctx.addIssue({
path: ['inputTwo'],
message: 'Input 2 is required when Option B is selected.',
});
}
});
2. Manage the State of the Form:
const [selectOption, setSelectOption] = useState(null);
const stepTwoForm = useForm({
resolver: zodResolver(stepTwoSchema.refine(
(data) => ({ ...data, select: selectOption }),
)),
});
Using .superRefine() in Zod for conditional validation based on the first step selection, you will be able to manage the state of the form to pass the data between steps easily
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With