Guides
Last Updated Aug 04, 2023

How to Validate a Phone Number with Node.js (and the Phone Validation API)

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Phone number validation has become increasingly important in the last few years. Not only is MFA ubiquitous for both web and mobile apps, but mobile apps, in particular, are moving away from the traditional username/password login method altogether. 

These days, providing a mobile number as the sole login method is a common user experience when signing up for a new mobile app. It goes without saying, then, that anyone building a mobile app needs to have some basic phone number validation in place.

Let’s send your first free
API
Phone Validation API
call
See why the best developers build on Abstract
Get your free api

Validation vs Verification

First, let’s talk briefly about the difference between validation and verification. You’ll need to do both when collecting a user’s phone number.

Validation

The process of validation (whether it be for a phone number or something else like an email address) involves checking to make sure the provided information is legitimate and accurate. Validation can tell you whether the user input characters that aren’t part of a phone number, or whether they input a number that doesn’t exist.

Verification

The process of verification involves checking whether the information the user provided is actually their information. In phone number verification, this means checking that the user has access to the device that the number belongs to. This is typically done by sending a verification code via SMS to the user’s phone.

The Free Phone Validation API doesn’t provide SMS message verification. For that, you’ll need to use a service or SMS API like Twilio. The Free Phone Validation API does, however, provide information that could help you verify that the number could reasonably be expected to belong to that user.

AbstractAPI Free Phone Validation API Overview

The AbstractAPI Free Phone Validation API is a lightweight, RESTful JSON API that provides validation for phone numbers from over 190 countries. 

Supported Languages

Because the Free Phone Validation API works via a simple REST endpoint, it is completely language-agnostic. It is incredibly simple and easy to implement, requiring no SDKs or additional libraries.

All you need to get started with the Free Phone Validation API is an API key, which you can acquire by providing an email and password after clicking the “Get Started” button on the API’s homepage.

Pricing

The free tier of the AbstractAPI Phone Number API supports up to 250 requests, which should be enough for anyone in the early stages of app development. 

From there, pricing increases to $9/month for the Starter Tier, which supports up to 1000 requests per month and 50 requests per second in a commercial environment. This Tier also provides email support. Startups with a small user base will probably find this tier sufficient.

The next tiers are Pro, at $49/month, and Enterprise, at $499/month. The Pro Tier supports up to 7000 requests per month at up to 500 requests per second, returns enriched premium data, and provides email support. The Enterprise Tier supports up to 75,000 requests per month, returns enriched data, and provides live chat support.

Security and Privacy

The AbstractAPI Phone Number Validation API is secured by 256-bit SSL encryption (HTTPS). All incoming requests must come via HTTPS. The API meets all GDPR and CCPA requirements and regulations.

How to Validate a Phone Number Using the API and Node.js

In this tutorial, we’ll cover how to get started using the AbstractAPI Phone Number Validation API, including how to acquire an API key and make requests. Next, we’ll look at what kind of response to expect from the API, and how to process that response and use it in your app.

We’ll be using Node.js, Yarn, and Axios in this tutorial. This tutorial will not cover Node basics, how to install or get started with Node, or how to build a simple Node.js app. If you’re unfamiliar with that process, check out this tutorial before proceeding.

Getting Started With the API

Acquire an API Key

  1. 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.
  1. Click the “Get Started” button. You’ll be taken to a page where you’re asked to input your email and create a password. Every AbstractAPI API requires a different key, so even if you have an existing API key from a different AbstractAPI API, you’ll need to provide your email to get a new one.
  1. You’ll land on a page that asks you to sign up for a paid plan—however, you can click “Back” in the top left corner to be taken to the free version of the API, which looks like this:

Make a Test API Request

Let’s use the provided “Make test request” button to send our first request to the API. 

  1. First, make sure that the “Live Test” tab is selected above the provided input box. Inside the box, you should see a URL. The URL points to version 1 of the AbstractAPI Phone Number API and includes a query string that contains your API key and an example phone number.
  1. Click the “Make test request” button. You should receive a 200 status and a JSON response. Let’s take a look at the response object:

{
    "phone": "14152007986",
    "valid": true,
    "format": {
        "international": "+14152007986",
        "local": "(415) 200-7986"
    },
    "country": {
        "code": "US",
        "name": "United States",
        "prefix": "+1"
    },
    "location": "California",
    "type": "mobile",
    "carrier": "T-Mobile Usa, Inc."
}

This is all of the information that will be returned to you about a phone number by the free version of the API. To get more detailed information, you’ll need to upgrade to a paid plan. 

Making an API Request Using Node.js

Now that we understand how to send an API request, and know what information we should expect to get back, let’s use the API to validate a phone number in a Node.js app.

Spin Up a Simple Node.js App

This tutorial assumes that you either have an existing Node.js app or that you’re familiar enough with Node to get one running on your computer. Refer to this tutorial if you need help with that.

Install an HTTP Client

If your app already has an HTTP Client installed, skip this step.

While the Phone Number API doesn’t require any SDKs or special libraries, you will need to have an HTTP client in your app in order to make requests. If you don’t already have one installed, we’ll quickly install the Axios client using yarn.

  1. Navigate to the root of your app directory
  2. Install Axios using Yarn via the command line
yarn add axios

Create a Route to Handle Phone Validation Requests

  1. Create a file called phone-validation.js. This is where you’ll handle all AbstractAPI Phone Number API requests and responses.
touch phone-validation.js
  1. Create a route in your index.js file to handle requests from the main app to the phone-validation.js handler

const phoneValidator = require('./phone-validation');
app.get('/validate', req, res, handlePhoneValidation);

async function handlePhoneValidation(req) {
    // we’ll write this later
    console.log(req);
}

We’ll write the handlePhoneValidation function in a subsequent step.

Make a Request to the API Using Axios

The AbsctractAPI provides a handy code snippet that we can copy into our app and use to make the request.

  1. Navigate to your free Phone Number API tester page
  2. Select the “Node.js” tab above the example input box
  3. Click the blue “Copy Code” button, or highlight and right-click to copy the provided code snippet

  1. Paste the snippet into your phone-validation.js file

const axios = require('axios');

axios.get('https://phonevalidation.abstractapi.com/v1/?api_key=YOUR_API_KEY&phone=14152007986')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.log(error);
    });

  1. Reformat the copy-pasted code snippet

The provided snippet is fine, but we can’t do much with the hardcoded string in there. Let’s do a bit of reformatting of the code so we can pass variables to the function. We’ll also make it easier to read. Also, we’ll use async/await to be consistent with the most modern Node.js practices


const axios = require('axios');
const apiURL = 'https://phonevalidation.abstractapi.com/v1/'
const apiKey = 'YOUR_API_KEY';

async function validatePhoneNumber(phoneNumber) {
  try {
    const response = await axios.get(apiUrl, {phone: phoneNumber, api_key: apiKey});
    return response.data
  } catch (error) {
    throw new Error(‘Caught in validatePhoneNumber: ’, error)
  }
}

module.exports.validatePhoneNumber = validatePhoneNumber;

Now, we’re able to pass in any phone number to the validatePhoneNumber function, and the function will make a request to the Free Phone Validation API, sending that number for validation. We wait for the response and then return the response data. 

Don’t forget to replace the API key temp string with your API key.

  1. Handle the response in your index.js file

Now that our validatePhoneNumber function is sending the request to the Free Phone Number Validation API, let’s write the handlePhoneValidation function and call the function from the ‘/validate’ route we created earlier in index.js. 


const phoneValidator = require('./phone-validator');
                               
app.get('/validate-phone', req, res, () => {
  const data = await handlePhoneValidation(req);
  res.send(data);
})


async function handlePhoneValidation(req) {
  try {
    const validatedData = await phoneValidator.validatePhoneNumber(req.query.phone);
    return validatedData
  } catch (error) {
    console.error(error);
  }
}

Here, we’ve called the validatePhoneNumber function from inside our ‘/validate-phone’ request handler, and passed in the phoneNumber parameter for validation. This assumes that you’ll be calling the endpoint and passing in the phone number you want to validate as a query string like “?phone=PHONE_NUMBER”.

Use the Validated Data

Once you’ve gotten your response object back from the API, you can process it and do whatever else you need to do with it. 

The most common use case will be pulling the valid boolean field from the object and returning that information to the client so the client can either proceed using the validated number or alert the user that the number was invalid.

Conclusion

As you can see, it’s easy to get up and running with the AbstractAPI Free Phone Number Validation API. AbstractAPI provides code snippets for this API for many languages, including C#, JavaScript/HTML, Laravel, Angular, jQuery, Java, Ruby, Python, PHP and Go. 

FAQs

What is the Phone Validator API?

A phone validation API checks to see whether a provided phone number is valid and still in use. Given a phone number, the API will return a boolean value of true if the number is a real number and is currently active. It will return false if the number is non-existent or not currently active.

The AbstractAPI Phone Validator API also returns some useful information about the phone number, such as location, country of registration, carrier, and whether the number is a landline, VOI, or mobile number.

How Does the Phone Validator API Work?

The Phone Validator API checks the given phone number against a number of databases. No actual calls are made during the phone number validation process. You can use the service to standardize numbers for your contact list and collect information about the user.

Does the Phone Validator API Send SMS Verification Codes?

No. The AbstractAPI Phone Validator API does not do SMS verification.

4.4/5 stars (12 votes)

Elizabeth (Lizzie) Shipton
Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.
Get your free
Phone Validation API
API
key now
Validate phone numbers instantly using Abstract's API.
get started for free

Related Articles

Get your free
API
Phone Validation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required