Building a Phone Number Verificator with JavaScript
Tags: tutorial, api, datavalidation, javascript
Published: 2022-06-07 09:00:14

There is little more annoying than running a business and not being able to contact (potential) customers. For emails, we have a common way to ensure the validity of addresses by simply sending a verification link. But what can we do about phone numbers? There is one sure way to validate phone numbers, and that is by using a number verifier for your contact form.
In this tutorial, I will show you how to build one with JavaScript in just a few simple steps. 

![This is what our number verificator will look like](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7wt3xbi262419wdxv42.png)

## Why build a phone number validator? 
Phone number validation is essential for capturing high-quality customer contact data and fraud prevention. If you want to ensure that your data is top-notch, a phone number validation API will be beneficial.

With a phone number verification API, you can keep your database clean. The API helps you automate your phone number lookup and validation process by pulling information from a global dataset. It allows you to capture and focus on good leads while keeping your registration forms spam-free and fighting fraud. 

## How to build a number verifier with JS
Before starting the tutorial, make sure you are working with the right tools. Our development stack should look something like this:

- [Yarn](https://classic.yarnpkg.com/en/docs/getting-started)
- [Vite](https://vitejs.dev/guide/)
- Tailwind CSS
- postcss
- autoprefixer
- numlookupapi
- Vanilla JavaScript

This is, of course, just a suggestion. You can replace whatever you want to a stack you are more comfortable with. 

Once the preparation is done, we can get started!

### 1. Initializing a Vite Project
The first step is initializing a Vite project in our development workspace:

`yarn create vite`

We now get asked for a project name, so choose whatever you want. We will also be asked to select a framework. Since we want to use plain JavaScript, we select vanilla (twice).

We can now switch into the newly created directory (as suggested by the console), but **do not start** the yarn build quite yet.

### 2. (Optional) Styling setup
We will use [Tailwind CSS](https://tailwindcss.com/) for easy styling, combined with autoprefixer & postcss for a smooth development experience. To do so, we install these packages:

`yarn add -D tailwindcss postcss autoprefixer`

After that, we can initialize tailwind, which will create a config file (tailwind.config.js):

`npx tailwindcss init`

Now, we need to adapt this new config to work with our Vite project setup:

```
module.exports = {
 content: [
   './main.js',
   './index.html',
 ],
 theme: {
   extend: {},
 },
 plugins: [],
}
```
To include Tailwind CSS, we add the following lines at the top of our style.css:

`@tailwind base;
@tailwind components;
@tailwind utilities;
`
And for postcss, we need to create a config file named `postcss.config.js` in our root directory and add the following lines:

```
module.exports = {
	plugins: [
    	require('tailwindcss'),
    	require('autoprefixer')
	]
}
```

### 3. Starting vite in dev mode
Now that our preparations are complete, we can start vite to serve our files with hot reloading:
`yarn dev`
This should automatically open up a new tab in your browser. If not, open `http://localhost:3000/` in any browser.
You should now see the default Vite index page reading `Hello Vite!`.

### 4. Preparing our HTML
Next, we need to adapt the default landing page.
We, therefore, open the index.html and build a form for phone number validation. For this, we need:

- A wrapper to hold our input: `<form id="phone_number_validator">` 

- An input for the phone number: `<input id="base_currency_input">` 
- A submit button: `<button type="submit">`
- A container where we display our response from the API: `<div id="result">` 

Here is what our implementation of the index.html looks like:
```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <link rel="icon" type="image/svg+xml" href="favicon.svg"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Phone number validator</title>
</head>
<body class="bg-gradient-to-b from-cyan-800 to-slate-800 min-h-screen py-5">
  <form
    id="phone_number_validator"
    class="mx-auto w-full max-w-sm bg-white shadow rounded-md p-5 space-y-3 text-sm">
<div class="flex items-center space-x-5">
    <label for="phone_number">Phone Number:</label>
    <input
            type="tel"
            id="phone_number"
            name="phone_number"
            placeholder="+123456789"
            value=""
            class="grow border-slate-300 border rounded-md py-2 px-4 text-sm"
            required
        />
    </div>
    <button
        type="submit"
        class="bg-slate-800 text-white rounded-md py-2 px-4 mx-auto relative block w-full"
    >Validate
    </button>
  </form>
  <div
    id="result"
    class="mx-auto my-5 w-full max-w-sm bg-white shadow rounded-md relative overflow-hidden text-sm empty:hidden divide-y divide-dotted divide-slate-300"
  ></div>
<script type="module" src="/main.js"></script>
</body>
</html>
```
All CSS classes are tailwind specific. Feel free to remove them entirely if you want to style it yourself or use another CSS framework.

We will use the id attributes in our JavaScript.

### 5. Handling form submission in JavaScript

In our main.js, we read the data from the input and send it to the number validation API. For this, we need an API key. In this tutorial, we use [numlookupapi.com](https://numlookupapi.com/) (they offer a free plan). The main.js could look something like this:

```
import './style.css'

const phoneNumberValidator = document.getElementById('phone_number_validator');
const phoneNumberInput = document.getElementById('phone_number');
const resultContainer = document.getElementById('result');

phoneNumberValidator.addEventListener('submit', (e) => {
	e.preventDefault();

	fetch(`https://api.numlookupapi.com/v1/validate/${phoneNumberInput.value}`, {
    	headers: {
        	apikey: 'YOUR-API-KEY'
    	}
	})
    	.then(response => response.json())
    	.then(data => {
        	if (data.message) {
            	resultContainer.innerHTML = `<div class="px-5 py-3 border-2 rounded-md border-red-500 text-600 px-5 py-3">${data.message}</div>`
        	} else {
            	const borderClasses = data.valid ? 'border-green-500' : 'border-red-500';

            	resultContainer.innerHTML = `<div class="space-y-1 px-5 py-3 border-2 rounded-md ${borderClasses}">
                    	<div class="flex items-baseline justify-between"><span class="font-medium">valid:</span><span>${data.valid}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">Carrier:</span><span>${data.carrier}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">Country:</span><span>${data.country_name}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">Country Code:</span><span>${data.country_code}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">Country prefix:</span><span>${data.country_prefix}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">International format:</span><span>${data.international_format}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">Local format:</span><span>${data.local_format}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">Location:</span><span>${data.location}</span></div>
                    	<div class="flex items-baseline justify-between"><span class="font-medium">Line type:</span><span>${data.line_type}</span></div>
                	</div>`;
        	}
    	});
});
```
**Note:** Make sure to replace `YOUR-API-KEY` with your actual key!

And that’s it! Now we have successfully built a phone number validator in JavaScript!

## Conclusion

Spam and fraud will be a thing of the past. A phone number validator lets you collect high-quality contact data and block fake accounts. With these five easy steps and the code provided, you can build your own validator. 
I hope this helps! Happy number validating :)!