Categories
JavaScript Answers

How to add validation using Yup to check string or number length with JavaScript?

Spread the love

Sometimes, we want to add validation using Yup to check string or number length with JavaScript.

In this article, we’ll look at how to add validation using Yup to check string or number length with JavaScript.

How to add validation using Yup to check string or number length with JavaScript?

To add validation using Yup to check string or number length with JavaScript, we call the test method.

For instance, we write

yup
  .string()
  .test("len", "Must be exactly 5 characters", (val) => val.length === 5);

to call test with 'len', an validation error string, and a callback to do the validation.

We check that the val has length 5 with (val) => val.length === 5.

Conclusion

To add validation using Yup to check string or number length with JavaScript, we call the test method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.