RECENT POST

TOP POST

Use JavaScript and Numverify to Verify Phone Numbers

by | May 17, 2024

Have you ever had problems with wrong phone numbers in your business? Checking phone numbers to ensure they’re correct is important for businesses. It helps keep customer details correct, improves communication, and ensures messages get to the right people. In this blog, we’ll discuss how to check and validate phone number using JavaScript, focusing on a phone number validator tool called Numverify.

Validating phone numbers isn’t just a technical thing. It’s key for keeping customer records accurate, improving communication, and ensuring messages reach who they’re meant for. We’ll explain why validating phone numbers matters for businesses and where you might use a phone number validator, like for:

  • Sign-ups
  • Contact forms
  • Sending messages.

Moreover, we’ll introduce Numverify as a tool for validating phone numbers, explain its benefits, and show how to use it with JavaScript. We’ll go through the steps, from setting up to testing with Numverify’s tools and building a basic example. Let’s begin.

Validate Phone Number using Numverify with  JavaScript

Why Do We Need to Validate the Phone Numbers for Our Businesses?

Here are some compelling reasons to implement phone number validation results for business performance:

💡Validating phone numbers helps ensure that the contact details you have for your customers are correct.

💡It ensures that messages and calls reach the right person. Furthermore, avoiding wasted time and effort.

💡In some places, there are rules about contacting people for marketing, and validating numbers helps you follow these rules.

💡Using invalid numbers or contacting people without their permission can lead to legal trouble.

💡Validating numbers can help you detect if someone is trying to use fake numbers for dishonest purposes.

What Are the Business Applications Where We Implement Phone Number Validation?

Here are some common places where businesses use phone number validation:

👉Sign-Up Forms

When people create accounts on websites or apps, validating their phone numbers helps make sure they’re real and can be contacted.

👉Contact Forms

On websites, validating phone numbers ensures that messages sent through contact forms can reach the right person.

👉Marketing

For text message marketing, validating phone numbers ensures messages are sent to real and active numbers, not wasted on invalid ones.

👉Customer Service

Validating phone numbers in customer support systems helps businesses communicate effectively with customers.

👉Security

Systems that use phone numbers for security validation ensure that only the right person can access an account. One such example is two-factor authentication to validate phone numbers.

👉Delivery Services

For businesses that deliver goods, validating phone numbers helps ensure delivery notifications reach customers correctly.

What Is the Best Tool for Businesses Phone Number Validation?

You can use a ready-made tool to validate international phone numbers or integrate it into your system. But how do you integrate phone number validation to get valid phone numbers into your systems? The answer lies in using the APIs. Don’t worry if you never used it before. We have written this guide as easy for beginners as for developers. Let’s begin.

Numverify

Numverify has a simple tool for checking phone numbers from around the world. It works for 232 countries.

Here’s what makes Numverify special:

1. It checks if a phone number is real by looking at the type of line it’s on and comparing it to the latest lists of numbers.

2. It uses trusted sources to make sure its results are accurate.

3. It works for both local and international numbers.

4. It keeps your information safe with strong encryption.

5. It comes with clear instructions and examples in different programming languages.

You can try Numverify for free to check up to 100 numbers every month. If you need more checks or extra features, paid plans are available.

How Do We Validate Phone Numbers Using Numverify and JavaScript?

Let’s begin working with the Numverify API.

Prerequisites

  • Numverify API Key
  • HTML
  • CSS
  • JavaScript

To get the Numverify API key, you should navigate to the Numverify website. Click on the Sign Up Free button as shown on the screen given below:

Numverify Bulk phone number validation tool or phone validator tool

Next, choose your preferred subscription plan and click on the Sign Up button.

Pricing plans for phone number validation work or phone verification tool

Fill out the below form to complete the registration process.

Phone validation work free plan

After you complete all the three steps given above, Sign In to your Numverify account. You will get a dashboard with the API Key as shown below:

Create an account at phone verification api for verifying phone numbers
Validate active phone numbers through our phone company api

Let’s test our API endpoints via Postman. Numverify gives access to the following API endpoints:

✔️Number Validation

✔️Country & Location

✔️National Numbers

✔️Carrier Detection

✔️Line Type Detection

✔️Countries Endpoint

Testing Numverify Endpoints Through Postman

Open the Postman website and create an account.

Create a new collection by following the below steps:

Postman testing to check mobile number active status using phone number validator tool

Paste the endpoint with the API key in the below bar by selecting the GET method:

Postman testing for personal and business numbers to check how experian data quality

Let’s suppose we are choosing this endpoint for testing:

http://apilayer.net/api/validate
    ? access_key = YOURAPIKEYHERE
    & number = 14158586273
Postman api request for phone validation api

👉Ensure you add your API key in place of the given placeholder “YOURAPIKEYHERE”.

Click on the send button, and you will get the API response in the Response section under:

API response

You should test all the endpoints in the same way. After you have tested and ensured that your API is working properly, the next step is to build the sample application.

Building the Sample Application

Open the Command Prompt and create a directory.

mkdir phonevalidapp

Next, open the directory inside your Visual Studio Code.

cd phonevalidapp

code . 

When the directory opens in Visual Studio Code, create a file called “index.html.” You can see it on the screen.

Visual Studio code

Let’s start writing code to build our phone number validation application.

First of all, you must set the HTML part of the code. Explaining every line may take a lot of time. Therefore, we will just explain the HTML, CSS, and JavaScript parts.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FoodAvengers App by APILayer</title>
<style>
/* Your existing CSS styles */
/* (CSS styles omitted for brevity) */
</style>
</head>
<body>
<!-- Login Container -->
<div class="container" id="login-container">
    <h1>Login</h1>
    <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" placeholder="Enter username">
    </div>
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" id="password" placeholder="Enter password">
    </div>
    <div class="form-group">
        <label for="phone">Phone Number:</label>
        <input type="text" id="phone" placeholder="Enter phone number">
    </div>
    <button class="btn" onclick="login()">Login</button>
</div>

<!-- Main Web Page Container -->
<div class="container" id="web-page" style="display: none;">
    <h1>FoodAvengers by APILayer</h1>
    <div class="form-group">
        <label for="currency">Select Currency:</label>
        <select id="currency" onchange="updatePrices()">
            <option value="USD">USD</option>
            <option value="EUR">EUR</option>
            <option value="GBP">GBP</option>
            <option value="PKR">PKR</option>
            <option value="CAD">CAD</option>
        </select>
    </div>
    <!-- Product List -->
    <div class="product">
        <img src="product_image_url" alt="Product A">
        <label for="product">Deal 1</label>
        <span class="product-price" id="productA">($10)</span>
        <button class="btn" onclick="addToCart('Deal 1', 10)">Add to Cart</button>
    </div>
    <!-- More products here -->
    <!-- Cart Section -->
    <div id="cart">
        <h2>Your Cart (<span id="cart-count">0</span> items)</h2>
        <table id="cart-items">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <div id="cart-total"></div>
    </div>
    <button class="btn" onclick="verifyPhoneNumber()">Place Order</button>
    <!-- Phone Verification Modal -->
    <div id="phone-modal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>Verify Phone Number</h2>
            <label for="order-phone">Phone Number:</label>
            <input type="text" id="order-phone" placeholder="Enter phone number">
            <button class="btn" onclick="validatePhoneNumber()">Submit</button>
        </div>
    </div>
</div>

<script>
/* Your JavaScript code here */
/* (JavaScript code omitted for brevity) */
</script>
</body>
</html>

<!DOCTYPE html>` declares the document type and version of HTML.

<html lang=”en”>` is the root element of the document, with the language attribute set to English.

<head> contains meta-information about the document.

<meta charset=”UTF-8″> specifies the character encoding.

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″> ensures the webpage is responsive.

<title>FoodAvengers App by APILayer</title> sets the title of the webpage.

<style> contains embedded CSS styles.

<body> contains the content of the webpage.

<div class=”container” id=”login-container”> is a container div for the login form.

<h1>Login</h1> is the heading for the login form.

<div class=”form-group”> groups each form input and label.

<label for=”username”>Username:</label> is the label for the username input.

<input type=”text” id=”username” placeholder=”Enter username”> is the text input for username.

<button class=”btn” onclick=”login()”>Login</button> is a button that triggers the login function.

<div class=”container” id=”web-page” style=”display none;”>` is the main container for the web page content, initially hidden.

<h1>FoodAvengers by APILayer</h1>` main heading for the web page.

<div class=”form-group”>` group for currency selection.

<label for=”currency”>Select Currency:</label> is the label for the currency dropdown.

<select id=”currency” onchange=”updatePrices()”> is the dropdown for selecting currency, which triggers `updatePrices()` on change.

<div class=”product”>` is a container for a product.

<img src=”product_image_url” alt=”Product A”> is the image of the product.

<label for=”product”>Deal 1</label>` is the label for the product.

<span class=”product-price” id=”productA”>($10)</span>` shows the price of the product.

<button class=”btn” onclick=”addToCart(‘Deal 1’, 10)”>Add to Cart</button> is a button to add the product to the cart.

<div id=”cart”> is a container for the shopping cart.

<h2>Your Cart (<span id=”cart-count”>0</span> items)</h2>` is the cart heading showing the number of items.

<table id=”cart-items”> is the table for cart items.

<button class=”btn” onclick=”verifyPhoneNumber()”>Place Order</button>` is the button to place the order, triggering phone number verification.

<div id=”phone-modal” class=”modal”> is the modal for phone verification.

<div class=”modal-content”> is the container for modal content.

CSS

👉The `body` style sets all text to use Arial font, making it clean and modern. It centers the text and removes default margins for a neat layout.

👉The `.container` class centers content on the page. It uses 80% of the page width and has automatic margins to align content well.

👉The `.product` class styles each product section. It adds padding and a border to make each product stand out. It also uses a light grey background to make products easy to see.

👉The `.cart` class styles the shopping cart table. It makes the table full-width and removes space between cells for a tidy look.

👉Buttons are styled with the `.btn` class. This adds padding, a light grey background, and rounded corners. When you hover over a button, it changes to a darker grey to show it’s clickable.

👉The modal for phone number verification is styled to be fixed in the center of the screen with a semi-transparent background. The `.modal-content` class adds padding and a white background to make text and input fields clear and easy to read.

You can also customize the CSS styles. Check the complete code at: https://github.com/devayesha23/Food_Ordering_App

JavaScript

<script>
const cart = [];

function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const phone = document.getElementById('phone').value;
    
    // Validate phone number using Numverify API
    const numverifyAccessKey = 'AddYourAPIKey';  // Replace with your Numverify API access key
    const numverifyApiUrl = `https://apilayer.net/api/validate?access_key=${numverifyAccessKey}&number=${phone}`;
    

    fetch(numverifyApiUrl)
        .then(response => response.json())
        .then(data => {
            if (data.valid) {
                // Sample username and password for demo purposes
                if (username === 'user' && password === 'password') {
                    document.getElementById('login-container').style.display = 'none';
                    document.getElementById('web-page').style.display = 'block';
                } else {
                    alert('Invalid username or password. Please try again.');
                }
            } else {
                alert('Invalid phone number. Please enter a valid phone number.');
            }
        })
        .catch(error => {
            console.error('Error validating phone number:', error);
            alert('Error validating phone number. Please try again later.');
        });
}

function addToCart(product, price) {
    let existingItem = cart.find(item => item.product === product);
    if (existingItem) {
        existingItem.quantity++;
    } else {
        cart.push({ product, price, quantity: 1 });
    }
    updateCart();
}

function decreaseQuantity(product) {
    let existingItem = cart.find(item => item.product === product);
    if (existingItem && existingItem.quantity > 1) {
        existingItem.quantity--;
        updateCart();
    }
}

function increaseQuantity(product) {
    let existingItem = cart.find(item => item.product === product);
    if (existingItem) {
        existingItem.quantity++;
        updateCart();
    }
}

function updateCart() {
    const cartItemsElement = document.getElementById('cart-items').getElementsByTagName('tbody')[0];
    cartItemsElement.innerHTML = '';
    cart.forEach(item => {
        const row = cartItemsElement.insertRow();
        row.innerHTML = `
            <td>${item.product}</td>
            <td>${getCurrencySymbol()}${(item.price * getCurrencyRate()).toFixed(2)}</td>
            <td>
                <button onclick="decreaseQuantity('${item.product}')">-</button>
                <span>${item.quantity}</span>
                <button onclick="increaseQuantity('${item.product}')">+</button>
            </td>
            <td>${getCurrencySymbol()}${(item.price * item.quantity * getCurrencyRate()).toFixed(2)}</td>
        `;
    });
    document.getElementById('cart-count').innerText = cart.reduce((sum, item) => sum + item.quantity, 0);
    const cartTotal = cart.reduce((sum, item) => sum + (item.price * item.quantity * getCurrencyRate()), 0);
    document.getElementById('cart-total').innerText = `Total: ${getCurrencySymbol()}${cartTotal.toFixed(2)}`;
}

const currencyRates = {};

async function fetchCurrencyRates() {
    const fixerApiKey = 'AddYourAPIKey';  // Replace with your Fixer API access key
    const fixerApiUrl = `http://data.fixer.io/api/latest?access_key=${fixerApiKey}`;

    try {
        const response = await fetch(fixerApiUrl);
        const data = await response.json();
        currencyRates['USD'] = 1;  // Base currency
        currencyRates['EUR'] = data.rates['EUR'];
        currencyRates['GBP'] = data.rates['GBP'];
        currencyRates['PKR'] = data.rates['PKR'];
        currencyRates['CAD'] = data.rates['CAD'];
    } catch (error) {
        console.error('Error fetching currency rates:', error);
    }
}

function getCurrencyRate() {
    const currency = document.getElementById('currency').value;
    return currencyRates[currency] || 1;
}

function getCurrencySymbol() {
    const currency = document.getElementById('currency').value;
    const symbols = {
        USD: '$',
        EUR: '€',
        GBP: '£',
        PKR: '₨',
        CAD: 'CA$'
    };
    return symbols[currency] || '$';
}

function updatePrices() {
    const currencyRate = getCurrencyRate();
    document.getElementById('productA').innerText = `(${getCurrencySymbol()}${(10 * currencyRate).toFixed(2)})`;
    document.getElementById('productB').innerText = `(${getCurrencySymbol()}${(20 * currencyRate).toFixed(2)})`;
    document.getElementById('productC').innerText = `(${getCurrencySymbol()}${(30 * currencyRate).toFixed(2)})`;
    updateCart(); // Call updateCart to refresh cart totals with the selected currency
}

// Fetch currency rates when the page loads
fetchCurrencyRates();

function verifyPhoneNumber() {
    const modal = document.getElementById('phone-modal');
    modal.style.display = 'block';

    const closeBtn = document.getElementsByClassName('close')[0];
    closeBtn.onclick = function() {
        modal.style.display = 'none';
    };
}

function validatePhoneNumber() {
    const phone = document.getElementById('order-phone').value;

    const numverifyAccessKey = 'AddYourAPIKey';  // Replace with your Numverify API access key
    const numverifyApiUrl = `https://apilayer.net/api/validate?access_key=${numverifyAccessKey}&number=${phone}`;

    fetch(numverifyApiUrl)
        .then(response => response.json())
        .then(data => {
            if (data.valid) {
                alert('Your Order is Placed, Our Agent will Call you Shortly.');
                const modal = document.getElementById('phone-modal');
                modal.style.display = 'none';
                // Reset cart and any other necessary actions
            } else {
                alert('Invalid phone number. Please enter a valid phone number.');
            }
        })
        .catch(error => {
            console.error('Error validating phone number:', error);
            alert('Error validating phone number. Please try again later.');
        });
}


</script>

Here’s a detailed explanation of each function and its purpose:

login()

It validates user credentials and phone number, then shows the main content of the app if the credentials are correct.

Steps:

  • Retrieves username, password, and phone number from input fields.
  • Constructs the Numverify API URL using the provided access key and phone number.
  • Fetches data from the Numverify API to check if the phone number is valid.
  • If the phone number is valid and the username and password match the hardcoded values (‘user’ and ‘password’), the login form is hidden, and the main content (#web-page) is displayed. If not, an error message is shown.

addToCart(product, price)

It adds a product to the shopping cart.

Steps:

  • It checks if the product already exists in the cart. If it does, it increments its quantity; otherwise, it adds a new entry to the cart.
  • Calls updateCart() to refresh the cart display.

decreaseQuantity(product) and increaseQuantity(product)

It decreases or increases the quantity of a product in the cart.

Steps:

  • Finds the product in the cart and adjusts its quantity.
  • Calls updateCart() to refresh the cart display.

updateCart()

It updates the cart display with current items, quantities, and total cost.

Steps:

  • Clears the current cart items display.
  • Iterates through the cart items and creates a row in the table for each item.
  • Updates the cart count and total cost.
  • Adjusts prices based on the selected currency.

fetchCurrencyRates()

It fetches currency conversion rates from the Fixer API.

Steps:

  • Constructs the Fixer API URL using the provided access key.
  • Fetches data from the Fixer API and stores the currency rates in the currencyRates object.

getCurrencyRate()

It retrieves the conversion rate for the selected currency.

Steps:

  • Gets the selected currency from the dropdown and returns its conversion rate from the currencyRates object.

getCurrencySymbol()

It returns the symbol for the selected currency.

Steps:

  • Gets the selected currency from the dropdown and returns its corresponding symbol from the symbols object.

updatePrices() updates product prices based on the selected currency.

Steps:

  • Gets the conversion rate for the selected currency.
  • Updates the displayed prices for each product using the conversion rate.
  • Calls updateCart() to refresh the cart totals with the selected currency.

verifyPhoneNumber() opens a modal to verify the phone number before placing an order.

validatePhoneNumber() validates the phone number entered in the modal.

Steps:

  • Retrieves the phone number from the input field.
  • Constructs the Numverify API URL using the provided access key and phone number.
  • Fetches data from the Numverify API to check if the phone number is valid.
  • If the phone number is valid, shows a success message and hides the modal. If not, shows an error message.

Get the complete code at: https://github.com/devayesha23/Food_Ordering_App

Output

When you run the app inside the Visual Studio Code, it shows the following web page:

App login form

Enter the username and password:

Username: user

Password: password

Enter your phone number to complete the login process. The system will verify phone numbers using Numverify. If you enter a valid phone number, you will be brought to the food page for ordering. If you enter invalid phone numbers, you will be shown a warning.

Number verification example
Food app

Before we add products to the cart, there is an interesting functionality that we want to tell you. We used the Fixer API by APILayer to convert the app’s currencies based on users’ preferences. You can see a dropdown “Select Currency” in the above image. When you choose it, you will see that prices are converted to your chosen currency. Here is an example when choosing PKR.

When you scroll down, you will also see a section that manages the items in the cart:

checking the your cart section
Adding items to place the order

When you click on the Place Order button after adding them to the cart, you will be asked to complete your order by entering your number. If the number is valid, it will say, “Your Order is Placed; our Agent will Call You Shortly.” Otherwise, it will ask you to add a valid phone number. This functionality also works by using the Numverify API.

Completing the order
Checking the phone number validation
Phone line type validation

Validate Phone Number: Conclusion

To validate phone number helps keep customer details accurate, improves communication, and ensures messages reach the right people. This blog shows how to check and validate phone numbers using JavaScript and the Numverify API. Businesses can avoid issues with wrong phone numbers, enhance customer satisfaction, and comply with legal requirements.

Validate Phone Number: FAQs

How do you validate a phone number?

Use JavaScript and the Numverify API to validate a phone number.

Can We Trust Numverify for the Phone Number Validation?

Yes. Numverify provides reliable and accurate phone number validation services.

How Do Businesses Integrate Numverify for Phone Numbers Validation?

Businesses integrate Numverify by using its API to validate phone numbers in their applications.

Is Numverify a Scalable Solution?

Yes. Numverify can validate phone number and scales well and handles high volumes of phone number validation efficiently.

Start validating phone numbers today to streamline your business operations.

Sign up free - Numverify phone number verification API