Search code examples
javascriptzod

zod - check if any of object properties pass validation


I have a schema like this:

z.object({
  name: z.string().min(3),
  email: z.string().min(3),
})

BUT I want to make it pas validation if at least one of these two properties pass validation. I wanted to do:

z.object({
  name: z.string().min(3),
  email: z.string().min(3),
}).refine((res) => res.name || res.email)

but there is still an error if any of the object properties fails and in refine I'm actually not checking if the valiadtion passes for name and email but I only check if they are defined. How to make it nice using zod?


Solution

  • Update your schema as below:

    z.object({
      name: z.string().min(3),
      email: z.string().min(3),
    }).or(
      z.object({
        name: z.string().min(3),
      }),
      z.object({
        email: z.string().min(3),
      }),
    );
    

    You can learn more here