Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation using Yup to check string or number length

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).

like image 762
reectrix Avatar asked Apr 17 '18 20:04

reectrix


People also ask

What does Yup string do?

Yup is a schema builder for runtime value parsing and validation. Define a schema, transform a value to match, assert the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformation.


3 Answers

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)

https://runkit.com/tamlyn/5ad9b99a4ba1230012d7ac21

like image 51
Tamlyn Avatar answered Oct 16 '22 07:10

Tamlyn


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

Demo: https://codesandbox.io/s/yup-y6uph

like image 32
SimoAmi Avatar answered Oct 16 '22 08:10

SimoAmi


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.

like image 33
efru Avatar answered Oct 16 '22 07:10

efru