How to Build a Phone Number Validator with JavaScript

Filed Under: Scripts
Phone Number Validator

Validating phone numbers is essential for collecting quality customer contact data and fraud prevention. If you want to make sure your data is top-notch, a number validation API will come in handy. This article shows you how to create a phone number verification web app using JavaScript.

What is a Number lookup API?

With a number validation API, you can keep your database clean and secure fresh insights, like how to reach your customers around the world. The API helps you automate your phone number lookup and validation process by fetching the information from a global dataset. It enables you to capture and focus on the good leads while keeping your registration forms spam-free and fighting fraud. 

A Step-by-step on how to create a phone number validation web app using JavaScript

In preparation for this tutorial, make sure your development stack looks something like this:

  • Yarn
  • Vite
  • Tailwind CSS
  • postcss
  • autoprefixer
  • numlookupapi
  • Vanilla JavaScript

If you are more comfortable with any other stack, feel free to replace whatever you want to your liking.

Phone Number Validator UI
A preview of the final phone number validator

Step 1: Initializing a Vite Project

We start by initializing a Vite project in our development workspace:

yarn create vite

A prompt in our console will now ask us for a project name (will create a folder of the same name), so choose whatever you want. As a next step, we will be asked to select a framework. Since we want to use plain JavaScript, we select vanilla (twice).

As suggested by the console, you can now switch into the newly created directory but do not start the yarn build quite yet.

Step 2: Styling setup (optional)

We recommend using Tailwind CSS for easy styling, combined with autoprefixer & postcss for a smooth development experience. To do so, install the following packages:

yarn add -D tailwindcss postcss autoprefixer

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

npx tailwindcss init

We now need to adapt this newly created config to work with our Vite project setup:

module.exports = {
 content: [
   './main.js',
   './index.html',
 ],
 theme: {
   extend: {},
 },
 plugins: [],
}

At the top of our style.css, add the following lines to include Tailwind 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')
	]
}

Step 3: Start vite in dev mode

With our preparations complete, we can now start vite to serve our files with hot reloading:

yarn dev

This should open up a new tab in your browser automatically. If not, open http://localhost:3000/ in a browser of your choice.

You should now see the default Vite index page reading Hello Vite!

Step 4: Prepare your HTML

The next step is to adapt the default landing page.
Open the index.html and build a form for phone number validation. We will need:

  • A wrapper <form id=”phone_number_validator”> to hold our input
  • An <input id=”base_currency_input”> for the actual phone number
  • A submit <button type=”submit”>
  • A container <div id=”result”> where we display our response from the API

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>

Note: All CSS classes are tailwind specific, so if you want to use another CSS framework or style it yourself, feel free to remove them completely.

We will use the id attributes in our JavaScript.

Step 5: Handle form submission in JavaScript

In our main.js, we read the data from the input and send it to the numlookupapi. For this to work, we need an API key. In this tutorial, we use numlookupapi.com; you can get a key for free. 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>`;
        	}
    	});
});

Make sure to replace YOUR-API-KEY with your actual key! Also, feel free to adapt the styling as you wish.

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

Collect quality customer data

With the help of your own number validator, you can make sure that the customer data you collect is high-quality and spam-free. It helps you prevent fraud and enables you to block fake accounts. Increase your acquisition and improve your contact rate by building a number validation web app in JavaScript in just a few steps.

close
Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors