user7505247
user7505247

Reputation:

Validation using Yup to check number length

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

Answers (2)

anerco
anerco

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

shili.oussama
shili.oussama

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

Related Questions