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.
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.
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.
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
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.
And start the app
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.
Next, create a top-level component called PhoneNumberInput and export it as a default export at the bottom of the file.
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.
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.
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>
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
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
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/>
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/>
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:
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
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
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.
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.
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.
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.