Created
November 25, 2019 11:47
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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