Yup Phone Number Validation

Last Updated Jun 23, 2022
Elizabeth (Lizzie) Shipton

Lizzie is a Full Stack Engineer at Udacity and freelance technical content writer. She has experience working with Node, GraphQL, Postgres, React and Sass.

Table of Contents:

Using a mobile number for authentication in your React application or mobile app is one of the most secure and efficient ways to authenticate your users. Validating user phone numbers is an important step in the authentication process.

In this article we’ll look at how to validate phone numbers with Yup, providing practical code snippets and examples. We’ll also look at an alternative phone number validation solution. 

Using Yup to validate phone number

Can You Do a Phone Number Validation Check With Yup?

Unfortunately, Yup does not include an out-of-the-box phone number validation method. However, by extending Yup with a package called yup-phone-lite, or with yup-phone, you can add a phone number validation check to Yup.

Yup Phone vs Yup Phone Lite

The yup-phone-lite package uses libphonenumber-js to add a phone check to Yup validator, while yup-phone is a validator using google libphonenumber. libphonenumber-js is a smaller package than google-libphonenumber, meaning that if you use yup-phone-lite, you will end up with a smaller bundle size.

Dependencies For Adding a Phone Number Validation Check to Yup Validator

As well as yup-phone or yup-phone-lite, another useful library for doing a phone number validation check is react-phone-number-input. This adds a phone number input component that takes a lot of the boilerplate out of collecting users' phone numbers.


$ npm install --save yup-phone yup react-phone-number-input

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

Phone Number Validation Check With Yup

Yup phone validation is easy with yup-phone-light. The yup-phone-lite package adds a phone number method to the basic Yup String type. This method takes the country of the phone number we are validating for, and an error message to show the user if validation fails. We can also chain the Yup String required() method to show a message if the user leaves the field blank.

Build a PhoneSchema

We can build a basic Yup schema object, using the .phone method as our validation method for a phone field. 



import * as Yup from "yup";
import "yup-phone-lite";

let phoneschema = Yup.object().shape({
  phone: Yup.string()
  .phone("US", "Please enter a valid phone number")
  .required("A phone number is required")
});

/pre>

Call ValidateSync

When we call phoneschema validateSync() on the schema and pass it the phone number from our input, Yup will validate the provided number against the schema. The phoneschema validateSync method does syncronous validation, as opposed to the regular Yup validate method, which is async. 



    const handleSubmit = () => {
        try {
            const isValid = schema.validateSync({phone: phoneNumber});
            if (isValid) {
                console.log("SUBMITTED! ", phoneNumber)
            } else {
                console.log("VALIDATION FAILED")
            }
        } catch (error) {
            setErrorMessage(error.message);
        }
    }

When you call phoneschema validateSync in your submit handler, Yup will validate the schema and raise errors, which you can catch and display to your user.

Using Yup for phone number validation check

Alternatives to Yup

Another way of validating a phone number is to use a dedicated phone number validation API like AbstractAPI’s Free Phone Number Validation API. This API checks the provided phone number against a database of numbers.

AbstractAPI ensures not only that the number is real and doesn't contain unexpected characters, but also gives you information about the number, like the specific location of the number, the carrier, and a few other useful things.

Conclusion

We’ve set up a basic phone input and explored two different phone number validation methods. There are many ways this can be improved. We need better styling on the input, and we also need to include a loading spinner for any asynchronous requests.

FAQs

How Can I Validate My Mobile Number In Yup?

Unfortunately, Yup does not provide out-of-the-box phone number validation as it does for email validation. However, you can extend Yup with yup-phone-lite, which adds a phone number method to the basic Yup String. You could also use yup-phone which is a Yup validator using google libphonenumber.

How Do I Do a Phone Number Validation Check?

There are three steps is fully validating a user’s phone number. The first is collecting the number from the user in some kind form field. Next, you must validate that the number is well-formatted and does not contain unexpected characters. Finally, you should verify that the user has access to the number by sending an SMS.

What Is Yup?

Yup is a JavaScript validation package that can be downloaded using a package downloader such as npm or yarn. Once added to your project, you can use it to create simple object schemas that can be used to either validate input or cast invalid input to a valid state. The best way to use Yup is to validate emails, phone numbers, passwords, and other fields in your forms.

Validate phone numbers instantly using Abstract's phone verification API.

Get started for free
Validate phone numbers instantly using Abstract's phone verification API.
Get started