Yup: Add example how to validate than one field matches another

Created on 11 May 2016  路  6Comments  路  Source: jquense/yup

I cannot find any example or appropriate function in the API how to make sure that one field has the same value as another (string in my case). Use case matching password and passwordRepeat fields.

I'm thinking I need to use ref, but I'm not sure how exactly. I was thinking of matches (but can I pass exact field value there) or oneOf.

yup.object().shape({
  newPassword: yup.string().min(5).required().label('New password'),
  reNewPassword: yup.string(),
});

Most helpful comment

The example that @jquense posted isn't working for me. This is what worked for me:

password: yup.string().required('Password is required'),
confirmPassword: yup.string().oneOf([yup.ref('password'), null], "Passwords don't match").required('Confirm Password is required'),

I got it from https://github.com/jquense/yup/issues/164

All 6 comments

ultimately it should be handled like: string().oneOf([ ref('password') ]), however oneOf doesn't currently support refs, due to some stuff with how they are managed.

in the meantime you can add a custom method to handle this:

yup.addMethod(yup.mixed, 'sameAs', function(ref, message) {
  return this.test('sameAs', message, function (value) {
    let other = this.resolve(ref);

    return !other || !value || value === other;
  })
})

string().match(ref('password'), 'passwords do not match')

@jquense Sweet! It works flawlessly!
We can close the case. Or we can add it somewhere in the docs/examples for others.

@chodorowicz This can be just:

string().oneOf([this.state.model.password], "Passwords don't match")

What's the resolve method? Where can I find the api docs? I see that this doesn't work with input with type='hidden'.

The example that @jquense posted isn't working for me. This is what worked for me:

password: yup.string().required('Password is required'),
confirmPassword: yup.string().oneOf([yup.ref('password'), null], "Passwords don't match").required('Confirm Password is required'),

I got it from https://github.com/jquense/yup/issues/164

I think those code samples should definitely be in the docs. They do explain a lot that is not in the docs now.

Was this page helpful?
0 / 5 - 0 ratings