Reputation:
Yup.number().test('len', 'Must be exactly 5 characters', val => val && val.toString().length === 5)
It's not working correctly. If this field empty, gives a " Must be exactly 5 characters", but should be show nothing.
Upvotes: 0
Views: 10409
Reputation: 107
add another check to return true if its empty/null/undefined
Yup.number().test('len', 'Must be exactly 5 characters', val => !val || (val && val.toString().length === 5))
Upvotes: 1
Reputation: 44
Try to add nullable() to your yup schema and a regular expression for the numbers, try something like this:
const regExp = /\b\d{5}\b/;
Yup.string().matches(regExp, {message: 'Must be exactly 5 numbers', excludeEmptyString: true})
Upvotes: 0