Validating password confirmation in Yup with React

Asked

Viewed 1,301 times

2

I have to validate a form where the user can update his password, I’m using Yup to do this.

My code is like this:

const schema = Yup.object().shape({
  name: Yup.string().notRequired().min(3, "O nome deve ter mais de 3 letras"),
  email: Yup.string().email().notRequired(),
  oldPassword: Yup.string().notRequired(),
  password: Yup.string().notRequired().min(6, "A senha deve ter pelo menos 6 caracteres"),
  confirmPassword: Yup.string().notRequired(),
})

I need to compare two fields, which are the password and the confirmPassword. Is there any way in Yup to verify that these fields are equal? I have tried matches() but it only works with regular expressions.

1 answer

2


By the method oneOf following the example:

validationSchema: Yup.object({
  password: Yup.string().required('Password is required'),
  passwordConfirmation: Yup.string()
     .oneOf([Yup.ref('password'), null], 'Passwords must match')
});

Reference: Check The Password Confirmation With Yup

in your code:

const schema = Yup.object().shape({
  name: Yup.string().notRequired().min(3, "O nome deve ter mais de 3 letras"),
  email: Yup.string().email().notRequired(),
  oldPassword: Yup.string().notRequired(),
  password: Yup.string().notRequired().min(6, "A senha deve ter pelo menos 6 caracteres"),
  confirmPassword: Yup.string().
      onOf([Yup.ref('password'), null],'Passwords must match')
})

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.