Skip to content

Instantly share code, notes, and snippets.

@hoodwink73
Created November 25, 2019 11:47
Show Gist options
  • Save hoodwink73/21e527a742a3c554ab27d771c9bd527f to your computer and use it in GitHub Desktop.
Save hoodwink73/21e527a742a3c554ab27d771c9bd527f to your computer and use it in GitHub Desktop.
Yup schema method to ensure a field value equals field value of another field. Useful for fields like confirm password field
// thanks 🙏
// https://github.com/jquense/yup/issues/97
function equalTo(ref, msg) {
return this.test({
name: 'equalTo',
exclusive: false,
message: msg || '${path} must be the same as ${reference}',
params: {
reference: ref.path
},
test: function(value) {
return value === this.resolve(ref)
}
})
};
yup.addMethod(yup.string, 'equalTo', equalTo);
const inst = yup.object({
account: yup.string().min(7).required(),
confirmedAccount: yup.string().equalTo(yup.ref('account'))
});
inst.validate({ account: '1234567', confirmedAccount: '12345678' }, {
abortEarly: false
}).then(function() {
console.log('ok', arguments);
})
.catch(function(error) {
console.log('failed', error);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment