Validating phone numbers is a critical step for maintaining data integrity in web forms and applications. We'll walk through five JavaScript implementation methods with code examples, explore the shortcomings of these traditional techniques, and demonstrate how Abstract API provides a more reliable alternative.
How to Validate Phone Numbers in JavaScript
There are several ways to implement phone number validation in JavaScript. Each method offers a different approach to check if a phone number's format is correct before processing it.
Regular Expression Checks
A regular expression, or regex, provides a direct way to check a string against a specific pattern. You can define a pattern for the international E.164 standard or for a specific country's format.
The E.164 pattern checks for an optional plus symbol followed by one to 15 digits. The US-specific example first removes all non-digit characters and then checks for a 10-digit number, with an optional leading '1'. This method only validates syntax.
const E164 = /^\+?[1-9]\d{1,14}$/;
function isE164(str) {
return E164.test(str);
}
const US = /^(1)?\d{10}$/;
function isUS(str) {
return US.test(str.replace(/\D/g, ''));
}
Google’s libphonenumber-js Library
This popular library from Google uses its own metadata to parse and validate numbers. It understands national numbering plans for more than 200 regions and can distinguish between a "possible" number and a "valid" one.
The library also normalizes numbers to the E.164 format and provides helper functions. The minified bundle is around 75 kB, while the full version is 140 kB. The code below parses a string and checks if it is a valid number.
import {parsePhoneNumberFromString} from 'libphonenumber-js/min';
const phone = parsePhoneNumberFromString('+1 213 373 4253', 'US');
if (phone && phone.isValid()) {
console.log(phone.formatInternational());
}
Native HTML5 Validation
The HTML5 input type 'tel' signals to mobile browsers that they should display a telephone keypad. You can add a regex to the pattern attribute for format validation during form submission.
The Constraint Validation API works with the form. The checkValidity method checks the input against the pattern. If the check fails, you can use setCustomValidity to display a custom error 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 JavaScript Phone Number Validation
Traditional JavaScript methods introduce practical challenges that compromise data quality. Each approach has inherent limitations that developers must consider before implementation.
- International numbering plans are complex. Country codes overlap with area codes, and number lengths vary widely. A single regular expression check often fails to account for these national quirks, which leads to incorrect validation results.
- Libraries like libphonenumber-js rely 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 syntactically correct number does not guarantee it is active. Static methods like regex checks or libphonenumber-js cannot confirm if a line exists due to factors like number porting, churn, or carrier blocks.
- User input is often inconsistent. People enter vanity words, stray characters, or omit prefixes. Simple parsers in HTML5 validation or regex must guess the user's intent, which can lead to hard-to-trace bugs.
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
Abstract API addresses the core weaknesses of traditional methods by moving validation to a single API call that checks against live telecom data.
- It moves beyond simple format checks to confirm if a number is currently active and routable.
- The API returns rich data points like carrier, line type, and location, which help with fraud detection and user segmentation.
- It eliminates the need for developers to maintain complex and ever-changing international numbering rules.
- A single HTTP call replaces heavy client-side libraries, so it avoids any impact on application bundle size.
How to Add Abstract API to Your Dev Environment
Once you know Abstract’s capabilities, you add its phone number validation API to your project with ease.
- Sign up at Abstract, enable the Phone Validation product, and copy your unique API key.
- Add the key to your runtime secrets store. For local development, you can export it as a variable.
- Write a thin client. JavaScript’s native fetch works well.
- Call the validation function in your signup or order flow. Inspect the returned flags to gate risky numbers.
- Monitor quota headers to receive alerts before you hit the free-tier limit.
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 with Abstract API
The function below sends a phone number to the API endpoint. The API then returns a JSON object with detailed validation results. The response confirms if the number is valid and provides useful context. This includes local and international formats, country data, location, line type, and the carrier. You can use this data for user segmentation or fraud detection.
// Sample JSON response from the API
{
"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."
}
Final Thoughts
Traditional validation methods often fail. They check format but cannot confirm if a number actually works. This approach creates false positives and requires constant updates to international rules.
Abstract API solves this with a single API call. It provides live data on validity, carrier, and line type. For reliable phone number validation, consider an account with Abstract API to get your free API key.
Validate Phone Numbers with Abstract API
Add phone number validation in JavaScript to prevent typos and collect accurate user information.
Get started for free