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).
I don't think there's anything built in but it's easy to implement with test
:
yup.string()
.test('len', 'Must be exactly 5 characters', val => val.length === 5)
I had to add a null checker, as it is possible that the val string is null because user hasn't typed anything yet
It works like a charm. Thanks a lot. We can also make it notRequired.
@Tamlyn Why do we use string().test() // test method here Is that the method which should be used or there's another method which would more suit it? Somehow .test() sounds more like a testing method...
But what with numbers where leading is 0 ? 000123.toString().length // : outputs 3 (not 6)