Yup: Validate only when field not empty \ compare fields are equal

Created on 11 May 2018  路  4Comments  路  Source: jquense/yup

If this has been answered before, I apologies. I did various searches but came up empty.

export const yupTest = yup.object().shape({
  firstName: yup.string().required('Please enter your First Name'),
  lastName: yup.string().notRequired().test('last_name', 'Last Name test message', function(value) {
    if (!!value) {
      return false; // this works as expected
    }
    return true; // <-- How do I do a sync test here like yup.string(value).min(2)
  }),
});

I have a few fields and only want to validate some IF the user has entered some data.

Also, how can I check if 2 fields are equal to each other (password === confirmPassword)?

Most helpful comment

This did the trick:

.oneOf([yup.ref('password'), null], "Passwords don't match")

Thanks for your help!

All 4 comments

mosts tests already ignore empty values, generally you can just add the test, and if you wnat to validate it being there also add required()

Thanks for your quick response!

I think I resolved the first question (although I am not sure if it's correct based on your response)

 export const yupTest = yup.object().shape({
  firstName: yup.string().required('Please enter your First Name'),
  lastName: yup.string().notRequired().test('last_name', 'Last Name test message', function(value) {
    if (!!value) {
      const schema = yup.string().min(2);
      return schema.isValidSync(value);
    }
    return true;
  }),
 });

What about comparing two fields for equality?

Thanks.

There are a few past issues on that, tho a bit hard to find. You can use ref() like string().oneOf([yup.ref('otherPassword')])

This did the trick:

.oneOf([yup.ref('password'), null], "Passwords don't match")

Thanks for your help!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

laurazenc picture laurazenc  路  3Comments

seanbruce picture seanbruce  路  3Comments

Simmetopia picture Simmetopia  路  4Comments

AmineIT picture AmineIT  路  3Comments

the-daniel-rothig picture the-daniel-rothig  路  4Comments