5

How to Build a Phone Number Validator with JavaScript

 2 years ago
source link: https://www.journaldev.com/62208/phone-number-validator-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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. 

00:00/01:37
liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTUjJaNypaZypyRcoWU9MTY1MmUkNwUmMlZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTA2NDM0JaN0YT0jJat9NwQjJax9NDQjJaZcZF9jYXNmRG9gYWyhPXq3ql5do3VlozFfZGV2LzNioSZmqWJJZD13q3phnz91pz5uoGRyqv5wo20zZGVvqWqJozZipz1uqGyiow0znXNBpHA9MCZlnT02QmY5NmY2NTUmNmQ2MTp0NmM3QmpmNxImMTqCNTQmMDqEN0I2NDMlMmAmMwMlMxQmMDM1MxQmMwM2NUYmMDMkN0Q3QwpmMmEmNwMjMmYmODM0MmUmNDqEN0I0MmMlMmQmNmqEN0I1MmY0MmM2NDMmNEM2RDpjNmY2NDU4NEE3NTU5NTp3ODZCNUE1ODU5NmU1OTMlMmx3NDqEN0I2MwYmNwt3MwZGNxQ2NTqEN0I3MTY0NwU3MmZCNmQ2RwpjN0Q3QwZGNxM2OTZFNmU3ODqEN0I1ODM2MmQmMDqEN0I1OTM0MmQmMDqEN0I2NwMkN0Q3QwRDMmxmNmM4Mmt3REZFRxUzZGyunWQ9JaVmZXJJpEFxZHI9NTAhNl4lNTMhMTplJaVmZXJVQT1No3ccoGkuJTJGNS4jJTIjJTI4WDEkJTNCJTIjTGyhqXtyMwB4ODZsNwQyMwxyMwB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DY0NDYzqWyxPVNyn2yhZG9TUGkurWVlNwI4ZWE4ZwUlMwM3MlZjqWJVpzj9nHR0pHMyM0EyMxYyMxZ3q3phnz91pz5uoGRyqv5wo20yMxY2MwIjOCUlRaBbo25yLW51oWJypv12YWkcZGF0o3IgnzF2YXNwpzyjqCZzoG9uqFN0YXR1pm1zYWkmZSZynWRmpD1jpzVvnWQ=

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:

  • 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK