Today I Learned

A Hashrocket project

Compare Form Values with Yup

We’ve been using yup to validate a JavaScript form, and found ourselves facing a common problem when a user signs up for a service:

How do we ensure a user’s email matches their email confirmation?

yup’s test function helped us find a solution. It’s documented like this:

mixed.test(name: string, message: string, test: function)

test takes a name, a message to show on failure, and a function that returns a boolean. We paired this with the email we get from our parent.

var schema = yup.object().shape({
  email: yup
    .string(),
  emailConfirmation: yup
    .string()
    .test('match', 
      'emails do not match', 
       function(emailConfirmation) { 
         return emailConfirmation === this.parent.email; 
       }),
}),