Guides
Last updated
July 20, 2025

5 Ways to Validate Phone Numbers with Regex

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

Validating phone numbers with regular expressions is a common first step in ensuring data quality for user-facing applications. We will explore five ways to implement this validation using regex, complete with working code snippets. We'll also examine the pitfalls of these traditional approaches and see how Abstract API provides a more reliable solution.

How to Implement Phone Number Validation in Regex

Regular expressions offer a direct way to check phone number formats. Here are four common regex-based methods to validate phone numbers, each with a distinct approach and code sample.

E.164-Only Validation

This method validates against the international E.164 standard. The pattern requires a number to start with a plus sign, followed by a non-zero digit, and then up to fourteen more digits. This approach works for any country because it checks the standard format, not a local one. A common version of this pattern appears on Stack Overflow.

e164 = re.compile(r'^\+[1-9]\d{1,14}$')
if e164.fullmatch(raw): …

Free-Form International Validation

This complex pattern accommodates many international formats. It supports an optional country code of one to three digits, an optional trunk '1', and various separators like spaces, dots, or hyphens. It also allows parentheses around the area code and accepts variable subscriber lengths. This type of expression is available in phone regex generators.

const intl = new RegExp(String.raw`^(\+\d{1,3}( )?)?1?\-?\.?\s?((\(\d{1,6}\))|\d{1,6})[- .]?\d{3,6}[- .]?\d{4,8}$`);
if (intl.test(raw)) { … }

Strict NANP Validation

This regex is tailored for the North American Numbering Plan (NANP), which covers the US and Canada. It looks for an optional "+1" prefix. The pattern ensures the three-digit area code does not start with a 0 or 1. It also uses alternation to accept area codes with or without parentheses, enforcing a total of ten digits. A similar US pattern appears in this reference table.

reNANP := regexp.MustCompile(`^(?:\+1\s?)?(?:\([2-9]\d{2}\)|[2-9]\d{2})[\s.-]?\d{3}[\s.-]?\d{4}$`)
reNANP.MatchString(raw)

Two-Pass Normalization and Validation

This technique involves two steps. First, a regex expression cleans the input string by the removal of any character that is not a digit, but it preserves a plus sign at the start of the string. This creates a canonical version of the number.

The second step applies business rules to the clean string. For example, the code can check if the number matches the E.164 format or a 10-digit NANP structure. This method works well when applications must store numbers in a single format but allow users to enter them in various ways.

# Step 1: Normalize
clean = re.sub(r'(?!^\+)[^\p{Nd}]', '', raw, flags=re.U)

# Step 2: Validate
if clean.startswith('+'):
    ok = bool(re.fullmatch(r'\+[1-9]\d{1,14}', clean))
elif len(clean) == 10 and clean[0] in '23456789':
    ok = True
else:
    ok = False

Challenges of Regex Phone Number Validation

While regex provides a quick filter, it presents significant limitations for robust validation. These patterns fail to account for the complexities and constant evolution of global phone number systems.

  • National numbering plans constantly change with prefix splits and length expansions. This makes hard-coded patterns like the Strict NANP method age out quickly, which causes them to reject or misclassify valid numbers.
  • Regex only confirms a number's format, not its real-world status. A string can match the Free-form international pattern perfectly yet correspond to an unassigned, retired, or reserved block of numbers.
  • Real-world input contains optional trunk digits, carrier codes, and various separators. A single comprehensive expression, like the Free-form international one, becomes unwieldy and fragile when it tries to account for this noise.
  • The E.164-only rule is too strict for common domestic formats. The two-pass normalization method hides complexity, where logic bugs in the second step can still accept invalid numbers.

Validate Phone Numbers with Abstract API
Implement proper phone number validation on your forms to maintain high data quality and reliability.
Get started for free

How Abstract API Handles Phone Number Validation

Abstract API addresses the core weaknesses of traditional regex methods by consulting real-time data instead of just pattern matching.

  • It consults a curated numbering-plan database and carrier feeds in real time. The API returns a boolean valid flag plus metadata like international or local formats, country codes, and carrier information.
  • The API possesses the format rules for more than 190 country patterns. This means your code does not need to track updates or unusual edge cases.
  • The response exposes a risk score and detects disposable or VoIP numbers, which regex cannot infer. You can feed this data into fraud-score models or contact-strategy logic.
  • Its low latency and enterprise-grade uptime eliminate the operational overhead that comes with regex updates across different applications.

How to Add Abstract API to Your Dev Environment

Once you're familiar with Abstract’s capabilities, the addition of its phone number validation API to your project is simple.

  • Create a free account at Abstract API and copy your unique Phone Validation API key.
  • Add the key to your secure configuration, for example, as an environment variable.
  • Install a preferred HTTP client, such as axios or node-fetch.
  • Construct the request URL: https://phonevalidation.abstractapi.com/v1/?api_key=$API_KEY&phone={PhoneNumber}.
  • Call the endpoint from your application and parse the JSON response.
  • Use the response fields, like "valid" or the risk score, to control downstream logic for signups or SMS delivery.
const fetch = (await import('node-fetch')).default;
async function validate(phone) {
  const url = `https://phonevalidation.abstractapi.com/v1/?api_key=${process.env.ABSTRACT_API_KEY}&phone=${encodeURIComponent(phone)}`;
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return await res.json();
}

Sample Implementation with Abstract API

The function above sends a phone number to the API endpoint. In return, Abstract API provides a detailed JSON object with validation status and rich metadata. This data allows you to confirm a number's existence at the carrier level and use details like location or line type for advanced logic.

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

The output confirms the number is "valid" and provides standardized "international" and "local" formats for display. The "country" and "location" fields help with geo-routing, while "carrier" and "type" can detect data mismatches or guide decisions about whether to call or send an SMS.

Final Thoughts

Traditional regex methods only check a string's pattern and cannot tell if a number is real or active. Abstract API overcomes these limits with real-time database and carrier lookups, which confirm a number's validity and provide valuable metadata.

For reliable user data, consider an account on Abstract API to get your free API key and validate phone numbers.

Validate Phone Numbers with Abstract API
Validate phone numbers to maintain data integrity and ensure you can reliably contact your users.
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