Guides
Last Updated Nov 21, 2023

How to Validate Phone Numbers using React.js

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

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 signingValidating phone numbers has become an indispensable part of modern app and website development. Phone numbers provide the most secure way to validate users and can be used to enhance the user experience in many ways.

React JS makes developing websites and apps faster and easier, especially when it comes to forms. React Hook Form and available libraries like libphonenumber-js and react-phone-number-input take much of the boilerplate out of building forms so you can focus on the more important aspects of data transfer and user experience.

Why Validate Phone Numbers?

There are several reasons you may want to validate phone numbers in your Javascript or Typescript app. The primary reason is for authentication and login. A valid phone number can be used instead of an email address for login or can be used for password-less login with SMS verification.

A valid phone number also helps to improve data completeness and helps you learn valuable information about your users. It can be used to determine things like geographic location for your users, which in turn can help you improve their user experience with targeted marketing and localized content.

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.

Let’s send your first free
API
Phone Validation API
call
See why the best developers build on Abstract
Get your free api

Basic Phone Number Validation in React JS

The easiest way to do phone number validation in React is using Regex. Regex (regular expressions) allow you to construct a pattern that can be used to match input strings.

There are many ways to write a regular expression for phone number matching. One way is the following:

const phoneRegex = new Regexp(‘^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$’)

This will match phone numbers of the following formats:

  • 123-456-7890
  • (123) 456-7890
  • 123 456 7890
  • 123.456.7890
  • +91 (123) 456-7890

To use this regular expression, you can simply pass it as the pattern attribute to an HTML phone input:

const PhoneNumberInput = () => {

 return (

   <div>

     <input type=’tel’ placeholder=’Enter phone number’ pattern=‘^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$’>

     </div>

 );

};

exportdefaultPhoneNumberInput;

This will allow the HTML5 input to do basic validation for you. If the number entered does not match the pattern, an error message will be raised to the user.

React Hook Form Phone Number Validation

React Hook Form takes a lot of the headache out of building web forms. It also provides built-in validation methods that allow you to easily validate any input field.

IMAGE: react-hook-form-logo

React Hook Form uses uncontrolled inputs and useRef to create a form that can be updated without depending on state. It provides a slew of out-of-the-box methods for form control, validation, and submission.

Let’s take a look at building a simple React component for phone number validation using React Hook Form.

Install Dependencies

Spin up a new app using Create React App using the following commands:

const PhoneNumberInput = () => {
$ npx create-react-app my-phone-validation-app

$ cd my-phone-validation-app

Next, install react-phone-number-input and react-hook-form.


$ npm install react-phone-number-input

$ npm install react-hook-form 

Start the app


$ npm start

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

Scaffold component

Inside src create a new file called phone-number-input.js alongside app.js and import dependencies.


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 React component called PhoneNumberInput.



const PhoneNumberInput = () => {

 return (

   <div>

     <p>This is where our phone input will go</p>

     </div>

 );

};

export default PhoneNumberInput;

Render component

Remove everything between the two <header> tags inside App.js and render the phone number input component instead using the following code:


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:

Add component logic

Create the React Hook Form wrapper inside phone-number-input.js using the components and handlers provided by React Hook Form. Write an onSubmit function. For now, this function will just log data to the console.


const {

   handleSubmit,

   formState: { errors },

   control

 } = useForm();



 const onSubmit = (data) => {

   console.log({data});

 };

The useForm hook gives us a handleSubmit function. Pass this to the onSubmit handler of the <form> element. When the user hits the return key or submits the form, this function will be called.

Delete the <p> tags from the component and instead render a form element that includes the <label>, and a <Controller>


<form onSubmit={handleSubmit(onSubmit)} className="phone-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 the react-phone-number-input code will go

           )}

           />

       </div>

       </form>

Notice that we name our controller “phone-input” because naming it will allow us to access it by name in the errors object later. We pass the control prop from the useHook hook to the <Controller>.


render={({ field: { onChange, value } }) => (

               <PhoneInput

               value={value}

               onChange={onChange}

               defaultCountry="US"

               id="phone-input"

               />

           )}

The render field accepts a function that returns a child component. It passes to the child component two values: an onChange handler, and a value. The child component we’re returning is the react-phone-number-input PhoneNumber component.

This means that React Hook Form takes care of updating the value of the form. We don’t write our own initial value, use setState, or write an onChange function.

Add validation

React Hook Form and react-phone-number-input make validation easy. Write a function that uses the isValidPhoneNumber method to validate a  provided phone number:


const handleValidate = (value) => {

   const isValid = isValidPhoneNumber(value);

   console.log(isValid);

   return isValid

 }

Log the isValid value to the console so you can see what’s going on before you return it. Next, add the function to the validation rules in the React Hook Form Controller component:


rules={{

           validate: (value) => handleValidate(value)

    }}

The validation function will be called every time the form value updates. Finally, render an error message if the phone number is invalid:


{errors["phone-input"] && (

           <p className="error-message">Invalid Phone</p>

      )}

We’re using the errors object provided by the React Hook Form formState. React Hook Form adds any errors that the React component encounters to the errors object under the same name we gave our input.

Mobile Number Validation in React JS

When you’re validating phone numbers in React JS, you are mostly validating mobile numbers. Mobile numbers are what pretty much everyone uses these days, and it is very unlikely you will ever need to validate another type of number.

Keep in mind that when it comes to validating mobile numbers, you should also verify the number by sending an SMS to the number with a validation code. This is a very secure way of validating the mobile number.

SMS validation is beyond the scope of this article, but some good services to look into to handle this part of the process include Twilio, sms-verification on Github, and Google’s SMS verification API.

Advanced React Phone Number Validation Techniques

If you want your phone number validation to be as robust as possible, you should use a phone number validation API in addition to Regex or the built-in validation methods provided by libraries. Let’s take a look at how to use AbstractAPI’s Free Phone Number Validation API to add an extra layer of validation to our existing app.

Get an API key

Navigate to the API documentation page. Click the “Get Started” button. You’ll be taken to a page where you’re asked to input your email and create a password.

Once you log in, you’ll land on the homepage of the Phone Number API, which looks like this:

Add API Validation to the Validation Function

First, install axios to send a network request.


$ npm install axios

Write a function that sends a network request to the API, containing the phone number for validation:


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)

 }

}

Now, call this function inside your existing validation function.

 const handleValidate = async (value) => {

   const isValid =  await validatePhoneNumberViaApi(value);

   return isValid

 }

This is now an async function. It will be called every time the React Hook Form updates. However, you won’t need to debounce the function: according to the validate documentation, React Hook Form allows you to pass an async function as a validator.

Use the Response

The response you get back from the API will be a JSON object 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."
}

We simply pulled the valid boolean value out of this object and used it to determine the validity of the provided phone number.

Common Pitfalls & Best Practices

The most difficult thing to do when it comes to validating phone numbers is to comply with the various different formats for international phone numbers. That’s why using a library like react-phone-number-input is such a great idea.

Libraries like this provide out-of-the-box solutions for users inputting their country code, and handle things like different number length, separators, etc. Combined with AbstractAPI for validation, you’ll be able to build a phone number input that handles all types of international number.

Finally, always remember to surface errors to your users in a readable and actionable way. Using the React Hook Form errors object will make this process easier.

Conclusion

These days, it’s best to use frameworks and libraries like React Hook Form and react-phone-number-input, combined with APIs like Abstract. These services not only make form-building more efficient, they also make it more secure and more robust.

Always prioritize user experience when it comes to web forms. This is often the first touchpoint users will have with your app, website, or brand. Make the experience a positive one!

4.8/5 stars (12 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Phone Validation API
API
key now
Enhance your app or website's user experience and security with Abstract's phone number validation API. Try it today to streamline authentication, improve data accuracy, and offer tailored content to your users!
get started for free

Related Articles

Get your free
API
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required