Guides
Last updated
July 20, 2025

5 Ways to Validate Phone Numbers in JavaScript

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
phone validation
 API key now
stars rating
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

Ensuring data quality in web applications often starts with phone number validation. This guide explores four ways to validate phone numbers in JavaScript, providing working code for each method. We'll also cover the pitfalls of traditional approaches and demonstrate how Abstract API overcomes these challenges.

How to Implement Phone Number Validation in JavaScript

This section details three distinct methods for JavaScript phone number validation. Each approach has a unique implementation, from simple pattern checks to comprehensive library-based solutions.

Regex-Only Check

Regular expressions, or regex, offer a direct way to validate phone number syntax. This method uses a pattern to check if a string conforms to a specific format and requires no external dependencies.

For example, the E.164 standard, which covers a plus sign followed by up to 15 digits, can be validated with a simple pattern. A similar approach works for country-specific formats like the US. The code defines functions that test a string against these patterns.

const E164 = /^\+?[1-9]\d{1,14}$/;   // ITU E.164
function isE164(str) {
  return E164.test(str);
}

// US domestic example
const US = /^(1)?\d{10}$/;
function isUS(str) {
  return US.test(str.replace(/\D/g, ''));
}

Google’s Libphonenumber-js

For more advanced validation, you can use Google’s "libphonenumber-js" library. This package includes Google's metadata and understands the national numbering plans for over 200 regions worldwide.

The library can differentiate between a "possible" number and a fully "valid" one. It also normalizes numbers to the E.164 format and provides helper functions. The NPM package comes in different bundle sizes. The code imports a function to parse a string, checks its validity, and formats it.

import {parsePhoneNumberFromString} from 'libphonenumber-js/min';
const phone = parsePhoneNumberFromString('+1 213 373 4253', 'US');
if (phone && phone.isValid()) {
  console.log(phone.formatInternational());
}

Native HTML5 Input

HTML5 provides built-in features for form validation with the “input type="tel"” element. This approach leverages the browser's native capabilities to check phone numbers without a separate JavaScript library.

On mobile devices, the browser displays a specialized telephone keypad. You can specify a regex in the “pattern” attribute to enforce a specific format for form validation. The JavaScript code uses the Constraint Validation API to listen for the form’s “submit” event. If the input is invalid, it prevents submission and can display a custom validation message.

<form id="f">
  <input type="tel"
         id="p"
         name="p"
         pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
         required>
</form>

document.getElementById('f').addEventListener('submit', e => {
  const inp = document.getElementById('p');
  if (!inp.checkValidity()) {
    inp.setCustomValidity('Use ###-###-####');
    e.preventDefault();
  }
});

Challenges of Phone Number Validation

While the methods above offer basic checks, they share fundamental limitations. These approaches often fail to account for the complex and dynamic nature of global and domestic telephone numbering plans.

  • International number plans present a major hurdle. A simple regex check struggles with varied lengths, overlapping country and area codes, and unique national dial quirks, which leads to frequent validation errors.
  • Libraries like libphonenumber-js depend on static metadata. Since numbering plans change faster than library updates, the validation for new or migrated phone number ranges can become inaccurate and produce false results.
  • A correct format does not guarantee a number is active. Static validation with regex or libraries cannot detect disconnected lines, temporary numbers, or ported numbers, so it only confirms syntax, not reachability.
  • User input is often inconsistent. People enter numbers with extra characters, vanity words, or ambiguous prefixes. This forces parsers in HTML5 or regex-based solutions to guess, which creates brittle logic.

Validate Phone Numbers with Abstract API
Implement phone number validation in JavaScript to ensure you're collecting accurate user contact information.
Get started for free

How Abstract API Handles Phone Number Validation

The Abstract API phone validation tool addresses the core weaknesses of traditional methods through a single API call that checks numbers against live telecom data.

  • It removes the operational burden to maintain and update international numbering rules on your own servers.
  • The API confirms if a number is live and routable, which eliminates false positives like correctly formatted but disconnected phone numbers.
  • It returns valuable data points such as the line type, carrier, and location to help with fraud scores or user sign-up processes.
  • Implementation requires one HTTP call, which avoids client-side bloat from large libraries.

How to Bring Abstract API to Your Dev Environment

Once you understand Abstract’s capabilities, you will find it simple to add its phone number validation API to your project.

  • Sign up at Abstract, enable the “Phone Validation” product, and copy your unique API key.
  • Add the key to your runtime secrets store.
  • Install cross-env or dotenv if you need key injection across multiple environments.
  • Write a thin client with JavaScript’s native fetch function.
  • Call the validation function in your user flow and use the response data to gate risky numbers.
  • Monitor quota headers to manage your usage and avoid service interruptions.
const base = 'https://phonevalidation.abstractapi.com/v1/?api_key=' + process.env.ABSTRACT_KEY;
export async function validatePhone(phone) {
  const res = await fetch(`${base}&phone=${encodeURIComponent(phone)}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

Sample Phone Number Validation Implementation with Abstract API

The function above sends a phone number to the API endpoint and returns a JSON object with comprehensive validation details. A successful request for the phone number "14152007986" produces the following output.

{
  "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."
}

Each field provides a specific piece of information:

  • A "valid" value of "true" confirms the number is live and routable.
  • The "format" object gives normalized versions of the number for display.
  • The "country" and "location" fields identify the number’s jurisdiction.
  • The "type" and "carrier" fields help with SMS route choices or fraud detection.

Final Thoughts

Traditional methods like regex only check format and fail to confirm if a number is live. Libraries add bloat without proof of reachability. Abstract API moves this work off your servers. It uses live telecom data to confirm validity and return details like carrier and line type. Consider an account on Abstract API to get your free API key and reliably validate user phone numbers.

Validate Phone Numbers with Abstract API
Add phone number validation in JavaScript to prevent typos and collect accurate user information.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
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