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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *