Conditional validation not working in useFieldArray #13073
Replies: 2 comments
|
If you want to have a conditional check based on z.object({
hasNoMiddleName: z.boolean(),
middle_name: z.string()
}).superRefine((data, ctx) => {
if (!data.hasNoMiddleName) {
if (data.middle_name.length <= 1) {
ctx.addIssue({
code: "custom",
message: t('form.errors.middle_name.required'),
path: ["middle_name"],
});
} else if (!/^[A-Za-z]+$/.test(data.middle_name)) {
ctx.addIssue({
code: "custom",
message: t('form.errors.middle_name.regex'),
path: ["middle_name"],
});
}
}
}); |
|
The unconditional Another option is to model the checkbox branches explicitly: const common = {
// Keep your existing id, first_name, last_name, birth_date,
// birth_country, birth_city, and gender validators here.
};
const child = z.discriminatedUnion('hasNoMiddleName', [
z.object({
...common,
hasNoMiddleName: z.literal(true),
middle_name: z.string().optional(),
}),
z.object({
...common,
hasNoMiddleName: z.literal(false),
middle_name: z.string()
.min(1, t('form.errors.middle_name.required'))
.regex(/^[A-Za-z]+$/, t('form.errors.middle_name.regex')),
}),
]);
const schema = z.object({ children: z.array(child) });This accepts an empty or omitted middle name when checked, and requires alphabetic content otherwise. A one-letter name such as Make sure the checkbox sends a Boolean, and preserve all your other field validators in Prepared with AI assistance. |
Uh oh!
There was an error while loading. Please reload this page.
Hi, I have an issue where i use react hook form with zod and need validation that is conditional (when checkbox is checked it should not validate certain field). I have implemented this in other forms and it uses identical logic except they are not using FieldArray and is not an array. Any suggestion is appreciated (conditional field is middle_name)
This is the schema
import { z } from 'zod';
component where it is used in custom hook
How useForm is implemented in useChildrenForm custom hook
All reactions