Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a field in Zod depending on the value of another field?

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

like image 365
Witcher Avatar asked Dec 03 '25 15:12

Witcher


1 Answers

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
});
like image 196
Sophie Rhodes Avatar answered Dec 06 '25 04:12

Sophie Rhodes