How to validate the password and confirm password using the react hook form and yup

Viewed 3709
const formOption = {
 config = [

      {
        label: 'Password',
        name: 'password',
        type: 'password',
        rules: yup.string().required()
      },
      {
        label: 'Confirm password',
        name: 'confirmpass',
        type: 'password',
        rules: yup.string().required()
      }
    ]
}

How to validate the password also the confirm password when its not equal using the react hook and yup?

cause what I'm trying to do is to add a validation when the confirm password is not equal to the password.

2 Answers

You can use the test() API like this

const formOption = {
 config = [

      {
        label: 'Password',
        name: 'password',
        type: 'password',
        rules: yup.string().required()
      },
      {
        label: 'Confirm password',
        name: 'confirmpass',
        type: 'password',
        rules: yup
                .string()
                .required()
                .test(
                 'passwords-match', 
                 'Passwords must match', 
                 (value) => this.parent.password === value)
                )
      }
    ]
}

See doc

You can do this with react hook forms alone. You can use watch from react hook form to get this done. This lets you listen for changes in the password field, which you can use in your confirm password validate method to compare the password with the confirm password field value as show below;

const {register, watch} = useForm();
<input
 {...register("password", {
  required: true
 })}
/>
<input
 {...register("confirm_password", {
  required: true,
  validate: (val: string) => {
    if (watch('password') != val) {
      return "Your passwords do no match";
    }
  },
 })}
/>

Copy pasted from my answer at How to validate password and confirm password in react hook form? Is there any validate property and message in react hook form to show errors?

Related