Is there a yup function that validates a specific length?
I tried .min(5) and .max(5), but I want something that ensures the number is exactly 5 characters (ie, zip code).
This check leads to the best validation experience:
Yup.string()
.required()
.matches(/^[0-9]+$/, "Must be only digits")
.min(5, 'Must be exactly 5 digits')
.max(5, 'Must be exactly 5 digits')
output:
12f1 // Must be only digits
123 // Must be exactly 5 digits
123456 // Must be exactly 5 digits
01234 // valid
11106 // valid
For future reference, if you're looking to validate a number (zip code), the above solution requires a slight tweak. The function should be :
Yup.number().test('len', 'Must be exactly 5 characters', val => val.toString().length === 5)
.length does not work on numbers, only strings.