I have a schema and I need to make it so that the role field is only validated when the value of the subject field is 1, otherwise the role should not be validated at all
const schema = z.object({
subject: z.number().default(0),
gender: z.object({
owner: z.number(),
stranger: z.number().array().min(1),
}),
age: z.object({
owner: z.number(),
stranger: z.number().array().min(1),
}),
role: z.object({
owner: z.number(),
stranger: z.number(),
}),
});
I tried to use the refine method but it was unsuccessful. In all the code examples that I looked at, the refine only processed the field on which this method was called. In my case, I need to process another field
You can handle such conditional validation using .refine(validator: (data:T)=>any, params?: RefineParams) - here
Example implementation:
const schema = z.object({
subject: z.number().default(0),
role: z.object({
owner: z.number(),
stranger: z.number(),
}),
}).refine(data => data.subject !== 1 || (data.subject === 1 && data.role), {
message: "Role field is required when subject equals 1",
path: ['role'] // Pointing out which field is invalid
});
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