Sometimes, we want to validate phone number with Yup and JavaScript.
In this article, we’ll look at how to validate phone number with Yup and JavaScript.
How to validate phone number with Yup and JavaScript?
To validate phone number with Yup and JavaScript, we use the matches method
For instance, we write
const phoneRegExp =
/^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
const schema = yup.object().shape({
phone: yup
.string()
.matches(phoneRegExp, {
message: "Invalid phone number",
excludeEmptyString: false,
})
.required(),
});
to call yup.string to validate that phone is a string.
Then we call matches to check if phone matches the phone regex value.
We check all the segments of any phone number in the world with the regex.
Conclusion
To validate phone number with Yup and JavaScript, we use the matches method