How to check confirm password with zod

Viewed 184

How do I check for confirm password with zod?. I want to validate for confirm password with Zod. I want Zod to compare my password with comparePassword

export const registerUSerSchema = z.object({
    firstName: z.string(),
    lastName: z.string(),
    userName: z.string(),
    email: z.string().email(),
    phone: z.string().transform(data => Number(data)),
    password: z.string().min(4),
    confirmPassword: z.string().min(4),
    avatar: z.string().optional(),
    isVerified: z.boolean().optional()
})
1 Answers

You can achieve this by tacking on a superRefine

export const registerUserSchema = z.object({
    firstName: z.string(),
    lastName: z.string(),
    userName: z.string(),
    email: z.string().email(),
    phone: z.string().transform(data => Number(data)),
    password: z.string().min(4),
    confirmPassword: z.string().min(4),
    avatar: z.string().optional(),
    isVerified: z.boolean().optional()
}).superRefine(({ confirmPassword, password }, ctx) => {
  if (confirmPassword !== password) {
    ctx.addIssue({
      code: "custom",
      message: "The passwords did not match"
    });
  }
});

If the passwords fail to parse for the base reason (not at least 4 characters) then that error will come through, but if the whole base object succeeds to parse, then the super refine check will happen.

Related