Search code examples
zod

How do I validate that a field has the same value as another?


I am trying to implement a validation that checks if the email field is the same value as the reemail field. I previously used Yup and you could do this with the oneOf method but I am not sure how one would do the same with Zod.

I tried using superRefine but it doesn't seem to work. This is my schema:

export const validationSchema = z.object({
    email: z.string().email({ message: "Enter a valid email." }).min(1, "This field is required."),
    reemail: z.string().min(1, "This field is required."),
}).superRefine((data, ctx) => {
    if (data.email !== data.reemail) {
        ctx.addIssue({
            code: z.ZodIssueCode.custom,
            message: "The emails do not match.",
            path: ["reemail"]
        });
    }
 });

Solution

  • Use refine as below:

    export const validationSchema = z
      .object({
        email: z
          .string()
          .email({ message: "Enter a valid email." })
          .min(1, "This field is required."),
        reemail: z.string().min(1, "This field is required."),
      })
      .refine(
        (values) => {
          return values.email === values.reemail;
        },
        {
          message: "The emails do not match.",
          path: ["reemail"],
        }
      );