Phone number validation is a crucial property of modern mobile and web apps. A mobile number is a very secure method of authentication, used not only as a way of signing users into apps and websites but also in multi-factor authentication.

If you plan to use a mobile number to authenticate users in your React app, there are several steps you will need to go through to validate and verify users’ numbers. The first step in this process is validating that the number a user has entered is a valid mobile number.

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

Common Problems With Phone Number Validation

Phone number validation is tricky, particularly when your app must handle phone numbers from many nationalities. All over the world, phone numbers have different formats. 

Number Length

In the US, phone numbers are 10 digits long (when the area code is included), but in Mexico, a valid phone number is 12 digits long. The maximum allowed length for an international phone number, according to the International Telecommunication Union (ITU) is 15 digits.

Delimiters

You run into a similar problem when it comes to delimiters (the characters that separate the numbers in a phone number) because they are different all over the world. Similarly, the way numbers are grouped in a phone number differs from country to country.

User Error

The final problems you commonly encounter with phone number inputs are user expectations and user error. Some people want to include their country code when entering a valid phone number. Some want to include delimiters and spaces while others don’t. Some will try to enter their area code, while others will not.

How to Build a Robust Phone Number Input

The most important thing you can do to make phone number validation easy for users is to have a form that makes it very clear what is expected of the user. Use proper form elements and enable autoformatting. Make it very obvious where to enter the country code (dropdown menus are helpful here.) Above all, provide clear instructions for your user on where and how to enter their phone number.

Validate a Phone Number in a React App

There are many ways to validate a phone number in React. Some are better than others. If you wanted to roll your own validator, you could use a regular expression to compare the number against an expected pattern. Or you could keep a dictionary of all valid international phone number formats and compare the inputted number against each entry.

Both of these approaches have problems. You’ll never be able to write a regular expression that captures all international phone number formats. And a dictionary of international formats might go stale or have inaccuracies that will need to be constantly updated.

A much better idea is to use a validation library or a dedicated phone number validation API. That way, the nitty-gritty of parsing, cleaning, and comparing a string of numbers is put on the library or API. All you have to do is collect the user’s number and pass it off to the validator.

How to Validate a Phone Number Using react-phone-number-input

In this tutorial, we’re going to validate a phone number using react-phone-number-input, an NPM package that provides a pre-made React component for phone numbers, along with a country code dropdown and a handful of methods for phone number validation and translation.

We’ll also use React Hook Form, a library that makes building forms and managing form state very easy.

1. Create a React app and install dependencies

If you already have a React App in development, skip this step. If you don’t understand what a React App is or how to use React, check out this tutorial on React, and this information on Create React App before proceeding.

To spin up a new app using Create React App, run the following commands in your terminal


$ npx create-react-app my-phone-validation-app
$ cd my-phone-validation-app

If you don’t have create-react-app or other needed dependencies installed, you will be asked to install them. We also need to install react-phone-number-input and react-hook-form.


$ npm install react-phone-number-input
$ npm install react-hook-form 

And start the app


$ npm start

This will open a new browser window with the app running at localhost:3000.

2. Build the phone number input component

Inside src create a new file called phone-number-input.js and import all needed dependencies at the top of the file.


import React from "react";
import { useForm, Controller } from "react-hook-form";
import PhoneInput, { isValidPhoneNumber } from "react-phone-number-input";
import "react-phone-number-input/style.css";

Next, create a top-level component called PhoneNumberInput and export it as a default export at the bottom of the file.


const PhoneNumberInput = () => {
 
 return (
   

This is where our phone input will go

); }; export default PhoneNumberInput;

For now, we are just returning a <div> with some text inside it, but later this is where our phone number input will go.

3. Render the component

Remove everything between the two <header> tags inside App.js. Instead of rendering the boilerplate code, we’ll render our phone number input component.

Import your new PhoneNumberInput and render it inside the header.


import PhoneNumberInput from './phone-number-input';

// Full App component code not shown
…
     <header className="App-header">
     <PhoneNumberInput/>
     </header>
…

Check out your browser window at http localhost 3000. You should now see something like this:

Congratulations! You’re rendering your React phone number app. Now we just need to add the input itself and the validation logic.

4. Add the component logic

Inside phone-number-input.js, let’s create the React Hook Form wrapper using the components and handlers provided by React Hook Form. We’ll also write an onSubmit function that logs our data. Eventually, this function will send the data to our backend, or to another API for further validation.


const {
   handleSubmit,
   formState: { errors },
   control
 } = useForm();
 
 
 const onSubmit = (data) => {
   console.log({data});
 };

The useForm hook gives us access to a handleSubmit function, which handles submission of our data. It must be passed to to the onSubmit handler of the <form> element, and it will be called when the user hits the “return” key.

Delete the text you added earlier and add the form element that includes the <label>, and a <Controller>


      <form onSubmit={handleSubmit(onSubmit)} className="user-info-form">
       <div>
           <label htmlFor="phone-input">Phone Number</label>
           <Controller
           name="phone-input"
           control={control}
           rules={{
               validate: (value) => handleValidate(value)
           }}
           render={({ field: { onChange, value } }) => (
             // this is where our react-phone-number-input will go
           )}
           />
       </div>
       </form>

Notice that we pass our onSubmit function as the only argument to the handleSubmit handler. We also name our controller “phone-input” (this will be important when we need to handle errors later.) We pass the control prop from the useHook hook to the <Controller>.

So far all we’ve done is set up the React Hook Form logic that helps us handle the form state. The render field on the <Controller> is where the actual phone input will be rendered. Let’s add that now


          render={({ field: { onChange, value } }) => (
               <PhoneInput
               value={value}
               onChange={onChange}
               defaultCountry="US"
               id="phone-input"
               />
           )}

The render field on the <Component> accepts a function that returns a child component. The function accepts one argument, the field object, which passes to the child component two values: an onChange handler, and a value for the component.

This takes a lot of the state management out of rendering the form. React Hook Form takes care of updating the value of the form, so we don’t have to write our own initial value, use setState, or write our own onChange function.

The component we’re returning is the PhoneInput component provided to us by react-phone-number-input.

Let’s check out our phone number app in the browser again

We’re rendering a complete phone number component already, and we haven’t had to write any boilerplate! Pretty neat.

5. Add validation logic

So far, we’ve rendered a phone number component that accepts a phone number, manages state for us, and calls a custom submit function when the form is submitted. The one thing missing is validation.

React Hook Form and react-phone-number-input make this part easy too. We can use the automagic rules field of the React Hook Form <Controller/> component, combined with the handy isValidPhoneNumber method provided by react-phone-number-input.

First, write a handleValidate function that uses the isValidPhoneNumber method to validate a give value


const handleValidate = (value) => {
   const isValid = isValidPhoneNumber(value);
   console.log({ isValid })
   return isValid
 }

We’ll log the isValid value so we can see what’s going on before we return it. Next, assign the handleValidate function to the rules field of the React Hook Form <Controller/>


    rules={{
           validate: (value) => handleValidate(value)
    }}

This will ensure that the validation function is called every time the value inside the form is updated. Finally, we will render a message for the user in the case that the phone number is invalid. Place the following code just underneath your <Controller/>


     {errors["phone-input"] && (
           <p className="error-message">Invalid Phone</p>
      )}

We’re using the errors object provided by the React Hook Form formState. Because we named our <Controller/> “phone-input”, any errors that the React component encounters will be added to the errors object under the field “phone-input.” By accessing this field on the errors object, we can render a message to the user should any errors occur.

Performing More Validation

Perhaps you want to get some further validation of a given phone number. In that case, using a phone number validation API like Abstract API’s Phone Number Validation API is a great idea. You can send any phone number to the API’s REST endpoint and get back a JSON object with a validation boolean and additional information about the number.

The returned object looks like this:


{
  "phone": "14152007986",
  "valid": true,
  "format": {
    "international": "+14152007986",
    "local": "(415) 200-7986"
  },
  "country": {
    "code": "US",
    "name": "United States",
    "prefix": "+1"
  },
  "location": "California",
  "type": "mobile",
  "carrier": "T-Mobile USA, Inc."
}

Let’s rewrite our handleValidate function to use the AbstractAPI phone verification instead of the isValidPhoneNumber method.

1. Get an API Key

In order to use the AbstractAPI endpoint, you’ll need an API key. Navigate to the API documentation page. You’ll see an example of the API’s JSON response object to the right, and a blue “Get Started” button to the left.

Click the “Get Started” button. You’ll be taken to a page where you’re asked to input your email and create a password. If you already have a AbstractAPI acount, you’ll be asked to log in. 

Every AbstractAPI API needs a unique key, so if you have an existing API key from a different AbstractAPI API, you’ll be given a new one for this API.

You’ll land on the homepage of the Phone Number API, which looks like this

2. Rewrite the handleValidate function to use the API

First, we’ll add axios, an HTTP client for React, to make the request to the API endpoint


$ npm install axios

Next, we’ll write a function that uses axios to send a GET request to the API endpoint, sending our API key and the phone number for validation in the request


const apiURL = 'https://phonevalidation.abstractapi.com/v1/'
const apiKey = 'YOUR_API_KEY';
 
async function validatePhoneNumberViaAPI(phoneNumber) {
 try {
   const response = await axios.get(apiUrl, {phone: phoneNumber, api_key: apiKey});
   return response.data.valid
 } catch (error) {
   throw new Error(‘Caught in validatePhoneNumber: ’, error)
 }
}

Here, we assign the result of the axios get request to a variable called response. The data field of that response object contains the JSON object with all the information about the phone number we sent for validation. We pull the valid boolean field off that object, and return it as the response.

Now we can call the new validatePhoneNumberViaAPI method inside our handleValidate function. We will need to turn the handleValidate function into an async function since now we are making an API request.


 const handleValidate = async (value) => {
   const isValid =  await validatePhoneNumberViaApi(value);
   return isValid
 }

Since this is now an async function, and it gets called every time the React Hook Form runs the rules, you might be wondering if you need to debounce the function. You don’t! If you check the documentation for validate in the React Hook Form register documentation, you’ll notice that React Hook Form allows you to pass an async function as a validator. 

Conclusion

As you can see, validating a phone number using React Hook Form and react-phone-number-input is very easy. Component libraries and state management systems mean it’s no longer necessary to try and roll your own validation components. Validation APIs like Abstract API’s validation API make getting detailed information about a given phone number easy as well.

FAQ

How do I validate a phone number in React?

Validating a phone number in React JS is easy—there are many libraries that can help you quickly build forms and handle validation. Two of the best libraries and frameworks for handling phone validation in a React app are react-phone-number-input and React Hook Form. Used together, these two packages provide out-of-the-box validation methods and form building scaffolding.

Another great way to do phone number validation in React is to use an external validation API. AbstractAPI’s Phone Number Validation API provides an easily accessible and secure REST endpoint to get validation and other information for any phone number.

How Does the AbstractAPI Phone Validator API Work?

The Phone Validator API checks the provided phone number against a set of databases containing phone numbers from over 19 countries. No actual calls are made during the phone number validation process, and no SMS messages are sent. You can use the service to standardize numbers for your contact list and collect information about the user’s phone number, as well as check if the number exists.

Why Do I Need to Verify a Phone Number?

Phone number verification and validation are two crucially important steps in the process of onboarding and authenticating your users. Phone number validation prevents the user from accidentally inputting a phone number that they don’t have access to, or inputting the number of another person. It keeps users’ identities and personal information secure and provides explicit consent from the user that they allow the use of their phone number by your app.

Validate phone numbers instantly using Abstract's API.

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