Help Needed with Zod Schema for Password Confirmation Validation #3412
Replies: 3 comments
-
What's the problem exactly? |
Beta Was this translation helpful? Give feedback.
-
Hello there, This is how I got mine to work. First, you need to create a password schema. I added additional validation rules: const passwordSchema = z
.string()
.min(8, { message: minLengthErrorMessage })
.max(20, { message: maxLengthErrorMessage })
.refine((password) => /[A-Z]/.test(password), {
message: uppercaseErrorMessage,
})
.refine((password) => /[a-z]/.test(password), {
message: lowercaseErrorMessage,
})
.refine((password) => /[0-9]/.test(password), { message: numberErrorMessage })
.refine((password) => /[!@#$%^&*]/.test(password), {
message: specialCharacterErrorMessage,
}); Then you can proceed to create the additional schema to handle password confirmation: export const updatePasswordSchema = z
.object({
currentPassword: z.string(),
password: passwordSchema,
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, {
message: passwordMismatchErrorMessage,
path: ['confirmPassword'],
}); I hope the above helps. |
Beta Was this translation helpful? Give feedback.
-
this would be the solution for your case. you can use refine to access the password value and use a simple string comparison to detect if they are equal or not, and throw error based on your case |
Beta Was this translation helpful? Give feedback.
-
Hello everyone,
I'm working on a form validation using the Zod library in JavaScript and I've run into an issue with validating that the
password_confirmation
field matches thepassword
field. Here’s how I definedmy schema:
Beta Was this translation helpful? Give feedback.
All reactions