Phone Number Regex Javascript Validator
Search...
⌘K
Phone Number Regex Javascript Validator
Search...
⌘K


Phone Number Regex Javascript Validator
The Phone Number Regex JavaScript Validator lets you instantly check if a number string follows a valid phone number format using JavaScript regex. It’s ideal for use in contact forms, signup flows, or any web app that captures phone inputs. Use this alongside our JavaScript Regex Tester to build and refine your own patterns, or pair it with the Email Regex JavaScript Validator for complete contact form validation. You can also encode validated numbers using the Base64 Encoder or generate secure tokens for phone-based login systems with the Token Generator.
[A-Z]
: uppercase letters[a-z]
: lowercase letters[0-9]
: digits\.
: a literal dot+
: one or more of the preceding*
: zero or more of the preceding?
: optional (zero or one)^
: start of string$
: end of string
Test your APIs today!
Write in plain English — Qodex turns it into secure, ready-to-run tests.
Regular Expression - Documentation
What is Phone Number Regex?
Phone number regex is a regular expression pattern that checks if a string matches a valid phone number format. The pattern can vary based on:
Country format
Mobile vs. landline
Use of symbols like +, -, (, ) or spaces
Phone Number Regex Pattern in JavaScript
Basic International Phone Number Regex:
/^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/
Pattern Breakdown:
^\+?
→ Optional + for country code[0-9]{1,4}?
→ Country code digits[-.\s]?
→ Optional separator(\(?\d{1,5}?\)?)
→ Optional area code with/without parentheses\d{1,5}
→ Prefix or number section\d{1,9}
→ Final part of the number$
→ End of string
When you're building forms to collect phone numbers—whether for contact, SMS notifications, or user profiles—users might enter numbers in a huge variety of ways. For example, all of the following are valid US-based numbers:
+1-202-555-0123
+44 20 7946 0958
(123) 456-7890
The use of throughout the pattern means any of these separator characters (hyphen, space, or dot) are permitted, or they may be omitted entirely. For example, both and will match, as will .
If you want to enforce consistent separators throughout the number (so users can’t mix, say, a space and a dash), you’d typically use a capturing group for the separator, like , and then reference it later in the pattern using a backreference like . This ensures that if a separator is used, it must be the same throughout. For instance, would match but would not. However, if you’d rather allow flexibility, omit the backreference and just repeat the separator sub-pattern as above—this is often more forgiving for real-world inputs.
Note: If you require strict format adherence, consider providing format hints to users on your form to guide their input and improve validation success.
This flexible pattern is a solid starting point for validating international and domestic phone numbers in a wide range of formats.
And that's just the tip of the iceberg! There are even more valid combinations out there, each with its own mix of separators, country codes, and spacing. Validating every possible variation by hand is a headache—but regex makes it simple and efficient to handle all these formats at once.
Code Example 1 – Basic Phone Number Validation
const phone = "+91-9876543210"; const pattern = /^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/; console.log(pattern.test(phone)); // true
Code Example 2 – Validate Multiple Numbers
const numbers = ["+1 800-123-4567", "1234567890", "(011) 2345 6789"]; const pattern = /^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/; numbers.forEach(num => { console.log(`${num} → ${pattern.test(num)}`); });
Covers a Wide Range of Formats
The regex pattern above is versatile enough to match a variety of phone number styles from around the world. Here are just a few examples of formats that this approach can validate:
International numbers with or without a plus:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+1 800-123-4567</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+44 20 7946 0958</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+31636363634</mark>
US and local formats:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">1234567890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">123-456-7890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">(123) 456-7890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">123.456.7890</mark>
Numbers with area codes in parentheses, with or without spaces:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+1 (415)-555-1212</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">(011) 2345 6789</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+1 (123)456-7890</mark>
Numbers with variable country codes and separators:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+12 123-456-7890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+123 075-63546725</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+12(415)-555-1212</mark>
This pattern is flexible enough to handle:
Optional country codes (1 to 4 digits)
Area codes with or without parentheses
Dashes, spaces, or dots as separators
Numbers with up to 15 digits (including country and area codes)
So, whether you're working with North American, European, or other international phone numbers, this regex should have you covered for most common formats.
If you need even more granular control or support for additional country-specific patterns, consider refining the pattern further or stacking additional validation checks based on your application's needs.
Code Example 3 – Validate Input in a Web Form
<input type="text" id="phoneInput" placeholder="Enter your phone number" /> <p id="status"></p> <script> const pattern = /^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/; document.getElementById("phoneInput").addEventListener("input", function () { const isValid = pattern.test(this.value.trim()); document.getElementById("status").textContent = isValid ? "✅ Valid Number" : "❌ Invalid Number"; }); </script>
Why Some Phone Numbers Fail Validation
If you’re wondering why something like (000) 999-5555 might not pass certain regex patterns, here’s what’s happening:
Some regexes require the separators between number groups—like spaces, dashes, or dots—to be consistent throughout the phone number. For example, if a pattern uses a capturing group for the first separator (like a space) and then references that captured character for the next separator, it expects all separators to match. So, a number using both a space and a dash (e.g., (000) 999-5555) would fail, because the separators aren’t the same.
To allow mixed separators (spaces, dashes, or dots in any combination), you’d typically adjust the pattern so each separator position is matched independently, instead of enforcing consistency via backreferences. This way, more phone number formats—including those with a mixture of symbols—will be considered valid.
How Backreferencing (\1
) Keeps phone number Separators Consistent
Regex patterns often use backreferences (like \1
) to enforce consistency within the matched string. In the context of phone numbers, suppose the separator—space, dash, or dot—can appear between sections: for example, "(123) 456-7890" or "123.456.7890".
Here's where backreferencing comes in handy:
([\-\s\.])?
captures an optional separator (dash, space, or dot) after your area code or number section.Later in the pattern, using
\1
tells the regex "the separator found earlier must be repeated here."
This means if there was a dash after the area code, only a dash can be used between the next number groups.
So, a string like "123-456-7890" matches because all separators are dashes. But "123-456.7890" wouldn't match since it switches from dash to dot—a consistency check courtesy of the backreference.
If you want to allow mixed separators, simply replace the specific backreference \1
with the broader pattern for any separator, but doing so opens the door to less standard formats.
Validating Only the Numeric Content
If you want to ensure a phone number contains exactly 10 digits—regardless of any spaces, dashes, parentheses, or formatting—it’s simple to filter out the non-numeric characters and check the result.
Here’s a quick way to do it in JavaScript:
const rawInput = "(123) 456-7890";
const digitsOnly = rawInput.replace(/\D/g, ""); // Remove non-digits
if (digitsOnly.length === 10) {
console.log("Valid 10-digit number");
} else {
console.log("Invalid number");
}
This method strips out everything except numeric characters, so formats like 123-456-7890
, (123) 456 7890
, or 1234567890
are all accepted as long as the actual digit count is ten.
You can easily use this approach to validate user input before storing, sending, or further processing the phone number in your application.
Digit Length Requirements by Country
When validating phone numbers, it’s important to account for country-specific digit requirements. Here’s a quick guide to the typical number of digits you’ll encounter in various regions:
Argentina: Expect either 8 to 13 digits in total, or formats split by a hyphen—3 to 6 digits, followed by 4 to 7 digits. If a country code is used (e.g., +54), its inclusion is mandatory, and the digits immediately follow.
United States: Standard phone numbers require at least 10 digits (not counting the country code). This covers both mobiles and landlines across the U.S. and Canada.
European Union: Many EU countries use 9 digits for local phone numbers, not including the country code or any leading zeroes.
India: Phone numbers comprise exactly 10 digits, usually paired with the +91 country code for international formats.
China: Numbers typically contain 10 or 11 digits. The country code (+86) precedes these in international formats.
Keep in mind, these rules serve as a baseline; always adjust your regex or validation logic based on the exact requirements for your users’ region.
Validating Phone Numbers With Country Codes Using ISD Lists
Need to ensure a phone number includes a valid country code? You can combine regex with an ISD code array to enhance validation—perfect for international signup forms or multi-region apps.
Here’s how it works:
Extract the digits from the input.
Check if the number is within a reasonable length (commonly, 8 to 16 digits).
Isolate the initial digits as a potential ISD (country) code.
Compare this code to a predefined list of valid ISD codes. If it matches, accept the number!
Example Approach:
const ISD_CODES = [
1, 44, 91, /* ...full ISD code list... */ 263
];
function validatePhoneWithISD(input) {
const digits = input.match(/\d+/g)?.join('') '';
if (digits.length < 8 digits.length > 16) return false;
const countryCodeLength = digits.length - 10; // Last 10 assumed as the main number
if (countryCodeLength > 0) {
const countryCode = parseInt(digits.slice(0, countryCodeLength), 10);
return ISD_CODES.includes(countryCode);
}
// No country code found, treat as local number
return true;
}
console.log(validatePhoneWithISD('91-9883208806')); // true
console.log(validatePhoneWithISD('1-800-1234567')); // true
console.log(validatePhoneWithISD('999123456')); // true (local, no ISD)
This approach lets you accept both local and international numbers, ensuring international users can’t slip in mistyped codes. For even tighter controls, throw in a regex pattern to capture proper separators. The ISD code match is what truly confirms the country code’s validity.
Handling Optional Country Codes and Separators
Sometimes phone numbers start with a country code like , which may or may not be followed by a dash or space (e.g., 1-800-123-4567, 1 800 123 4567, or just 800-123-4567). To handle these, regex grouping and optional quantifiers come in handy.
For example, if you want your regex to optionally match a leading (the US country code), possibly followed by a space or dash, you can use:
^(1[ -]?)
groups the and the potential separator together.
The after the group makes the entire (and the separator after it) optional.
Combining this with the rest of a standard US phone number pattern, you get:
/^(1[ -]?)?\d{3}[ -]?\d{3}[ -]?\d{4}$
This matches:
1-800-123-4567
1 800 123 4567
800-123-4567
These are commonly accepted by robust patterns for North American numbers, as well as many international regexes with country code support.
Making Groups Optional in Regex
Sometimes, you need to make a whole sequence of elements optional, not just a single character. For example, in North American phone number formats, it's common to allow an optional leading (the country code), sometimes followed by a space or hyphen. To accomplish this in regex, group the elements you want to make optional with parentheses and then add a after the group.
Example:
To match numbers that may or may not start with , followed by an optional space or hyphen, you’d use:
^(1[ -]?)?\d{3}[ -]?\d{3}[ -]?\d{4}$
Here’s what’s happening:
The group matches an optional , possibly followed by a space or hyphen. The entire group is optional thanks to the trailing .
The typical 10-digit phone number format, with optional separators.
Grouping and making parts of your pattern optional is key for flexible validation, especially for formats like phone numbers that vary by region or user input habits.
US Number Example Pattern Breakdown:
Optionally start with (with optional space or dash)
Area code
Optional separator
Prefix
Optional separator
Line number
By combining these strategies, your regex can flexibly match a wide variety of international and domestic phone number formats, handling optional country codes, spaces, dashes, and parentheses commonly found in real-world data.
Common Valid US Phone Number Formats
This regex is flexible enough to match a wide variety of real-world phone number formats, especially those commonly seen in the US. Here are some examples of valid US-based numbers it will accept:
202-515-5555
202 515 5555
(202)515 5555
1 202 515 5555
2025155555
1-202-515-5555
1202-515-5555
and more
Not accepted:
555-5555 (to accept, use a pattern that allows 7-digit numbers)
5555555 (same as above)
1 555)555-5555
123**&!!asdf#
(6505552368)
Numbers with leading digits not matching U.S. Standards, such as 2 (757) 622-7382 or 10 (757) 622-7382
Whether the number uses spaces, dashes, or parentheses, or includes a leading country code, this pattern adapts to most practical scenarios you'll encounter in web forms and user input.
What About Short Numbers?
If you need to accept formats like or (US 7-digit numbers), you’ll want to adjust your pattern accordingly. For example:
/^+?1?\s*?(?(\d{3})?(?:)[-\s])?\s*?\d{3}[-\s]?\d{4}$/
This regex will accept both 7- and 10-digit numbers with or without formatting.
Rejected Formats (for standard patterns):
or (unless you use a relaxed pattern as above)
(misplaced parenthesis)
(non-numeric, invalid symbols)
Numbers with too few or too many digits, or with misplaced separators, e.g., , ,
Overly long numbers like
Sample JavaScript Validation Function:
js function telephoneCheck(str) { var patt = new RegExp(/^+?1?\s*?(?\d{3}(?:)[-\s])?\s*?\d{3}[-\s]?\d{4}$/); return patt.test(str); } Test it with: js telephoneCheck("+1 555-555-5555"); // true
Final Thought:
Always balance thoroughness with user experience—accept all valid real-world inputs, but keep your regex as simple as possible for your use case. And remember, for complex, production-grade validation, a dedicated library can save you time and headaches.
How to Build a Generic Phone Number Validator That Ignores Non-Digit Characters
Want to validate a phone number regardless of its formatting—parentheses, dashes, or spaces? You can easily create a flexible JavaScript function that strips out everything except digits, then checks the length to match your country or app requirements.
Here’s a step-by-step approach:
Remove Non-Digit Characters:
UseString.prototype.replace()
with the/\D/g
regex to clear out anything that's not a digit.Count the Digits:
Once you have a string of pure digits, check if its length fits your desired range. For example, the US and Canada typically expect 10-digit numbers for local calls, while countries like India may have 10 or 11 digits with a country code.Parameterize for Flexibility:
You can make your function accept minimum and maximum digit counts for global compatibility.
function isValidPhoneNumber(input, minDigits = 10, maxDigits = 14) {
// Remove all non-digit characters
const digits = input.replace(/\D/g, "");
// Check if the digit count is within the expected range
return digits.length >= minDigits && digits.length <= maxDigits;
}
// Usage examples:
isValidPhoneNumber("+1 (800) 123-4567"); // true
isValidPhoneNumber("98765-43210", 10, 10); // true for Indian mobile numbers
isValidPhoneNumber("(011) 2345 6789", 10, 11); // true for larger range
Tips:
Adjust
minDigits
andmaxDigits
to support regional formats or enforce local rules.This method ensures user input is valid regardless of formatting quirks—spaces, dashes, or fancy parentheses are all ignored.
For more complex checks (like country-specific starting digits), combine this with regex or prefix validation.
Now you can confidently handle almost any phone number format users throw your way!
Validating Toll-Free Numbers (800, 900, etc.)
Need to single out special numbers like toll-free or premium-rate lines in the US (think 800, 888, 877, 866, or 900)? You can fine-tune your regex to specifically match these patterns.
Here's an example regex that matches common US toll-free and 900 numbers:
/^(?:\+?1[-.\s]?)?(?:800888877866855844833900)[-.\s]?\d{3}[-.\s]?\d{4}$/
This pattern covers:
Optional country code (+1)
Supported prefixes (800, 888, 877, 866, 855, 844, 833, 900)
Flexible separators (spaces, dashes, dots)
Standard 7-digit phone segment
Usage example:
const tollFreePattern = /^(?:\+?1[-.\s]?)?(?:800888877866855844833900)[-.\s]?\d{3}[-.\s]?\d{4}$/;
console.log(tollFreePattern.test("1-800-123-4567")); // true
console.log(tollFreePattern.test("(900) 555-0000")); // true
console.log(tollFreePattern.test("8881234567")); // true
Tip: Adjust the prefixes inside the pattern as needed for your region, or combine this with your general validator to catch and handle special number categories in your forms and backend systems.
Validating and Formatting Phone Numbers Without Double Spaces or Hyphens
When it comes to phone number validation, especially for international formats, your regex needs to be flexible—but not too permissive. A robust pattern should accept variations with country codes, area codes (sometimes in parentheses), and allow for separators like spaces or hyphens, all while eliminating common issues such as double spaces or consecutive hyphens.
Sample Regex for Flexible Phone Numbers
Here’s an improved pattern that captures a wide range of phone number formats and prevents double spaces or hyphens:
const phonePattern = /^(\+?\d{1,4}[\s-]?)?(\(?\d{1,5}\)?[\s-]?)?(\d{1,5}[\s-]?){1,4}\d{1,9}$/;
Enforcing Clean Formatting
To ensure you don’t accept numbers with double spaces or double hyphens, you can run a quick check alongside your main validation:
function hasNoDoubleSeparators(num) {
return !(/[\s-]{2,}/.test(num));
}
Combine it with your validation logic:
function isValidPhoneNumber(phoneNumber) {
return phonePattern.test(phoneNumber) && hasNoDoubleSeparators(phoneNumber);
}
What This Covers
This approach will validate numbers like:
+44 07988-825 465
+44 (0) 7988-825 465
123 456-789 0123
123-123 123
123 123456
1234567890
Bonus: It won’t allow double spaces or hyphens anywhere in the phone number, ensuring cleaner, more standardized input for your database, forms, or APIs.
Feel free to tweak the pattern for your country-specific requirements!
Ensuring Regex Adheres to NANP Rules
If you want your phone number regex to strictly follow North American Numbering Plan (NANP) formatting, you’ll need to tighten up the validation logic—basic digit matching is only half the story.
Key NANP Requirements
Area Code and Exchange Format:
Both the area code and the exchange (the next three digits) must begin with a digit from 2–9, not 0 or 1.N11 Restriction:
Standard area codes and exchanges can’t end in “11” (to avoid overlap with service numbers), with exceptions for toll-free and premium area codes like 800 or 900.Structure:
The learned format isNXX-NXX-XXXX
, whereN
= [2–9] andX
= [0–9].Country Code +1:
For international compatibility, start the regex with+1
(optionally), along with common separator support.
Recommended Regex Pattern
For stricter NANP compliance, here’s an improved version:
/^\+1[-.\s]?([2-9][0-9]{2})[-.\s]?([2-9][0-9]{2})[-.\s]?([0-9]{4})$/
[2-9][0-9]{2}
ensures area and exchange codes start with 2–9.Separators
[-.\s]?
match dashes, dots, or spaces.Supports an optional “+1” prefix.
[-.\s]?
is part of the pattern matches any one of the separator characters—dash (), dot (), or whitespace ()—and makes it optional. In other words, it allows for phone numbers to be written with or without separators between number groups.
For example, , , or would all match, as well as . This flexibility is achieved because the makes the separator optional.
If you want to ensure consistency in separators (so the same character is used throughout the number), you can use a capturing group and backreference:
captures an optional separator.
matches three digits.
reuses the captured separator, requiring it to be the same for each segment.
With this approach, a number like (using both a space and a dash) would not validate, as the separators differ. If you prefer to accept mixed separators or nonstandard formats, you can simply remove the backreference () and keep the separator sub-pattern.
Regardless of the approach you take, consider providing a format hint to users so their input matches your expectations.
Important Considerations
International Numbers:
This regex strictly enforces North American formats. For global support, consider using libraries like libphonenumber (https://github.com/google/libphonenumber) that specialize in international phone validation.Server-Side Validation:
Regex validation in the browser helps users catch errors early, but always revalidate phone numbers securely on your backend.
By adjusting your pattern as above, you’re far more likely to reject invalid NANP numbers and accept only those that truly fit the regional rules.
Strict vs. Loose Phone Number Validation in JavaScript
When validating phone numbers with JavaScript regex, the level of strictness can make a big difference in user experience and accuracy.
Loose validation is forgiving—it accepts a wide variety of phone number formats. This means users can enter their numbers with different separators (dashes, spaces, dots), parentheses, or even with or without a country code. Examples of inputs a loose regex might permit include:
(123) 456-7890
+31636363634
123-456-7890
123.456.7890
The main advantage? Users don't get blocked by formatting requirements they may not expect. Especially in forms like registrations, this reduces friction and form abandonment. The trade-off is that loose patterns won't catch typos or malformed numbers—for example, they may accept too few or too many digits.
Strict validation, on the other hand, enforces a precise expected format. These regex patterns will only match well-defined phone number styles: requiring specific lengths, country codes, or exact arrangements of separators and digits. If you want to guarantee clean, predictable data—for example, before storing numbers in a database or for integrations with services like Twilio—strict validation is the safer bet. However, users might find it restrictive if they aren't sure of the expected input style.
In practice:
Use loose validation when you want to cast a wide net and are ready to clean or format numbers after submission.
Use strict validation if downstream processes (like SMS verification) require consistently formatted numbers.
Most developers find a balance—allow flexible input, but normalize and validate further before saving or processing. Consider your audience, the importance of data quality, and your backend requirements when choosing between strict and loose validation approaches.
Tips for Flexible and Reliable Phone Validation
Rather than getting stuck on specific formats, consider validating the numeric content directly. For example, you can strip out all non-digit characters and check if the result matches standard North American numbering:
var originalPhoneNumber = "415-555-1212"; function isValid(p) { var phoneRe = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/; var digits = p.replace(/\D/g, ""); return phoneRe.test(digits); }
If you need to support custom or evolving formats, try building your regular expression from a clear template string. This makes it easy to add new patterns—whether you're a developer or simply updating options in a settings page:
var formats = "(999)999-9999999-999-99999999999999"; var r = RegExp("^(" + formats .replace(/([()])/g, "\$1") .replace(/9/g,"\d") + ")$" );
This approach keeps your validation logic both transparent and easy to maintain, letting you adapt as your needs change.
Pro Tips
Always .trim() input to remove accidental whitespace from the user.
If you only need Indian mobile numbers, simplify the regex to:
/^[6-9]\d{9}$/
Strictly need 10 digits?
If your use case requires exactly 10 digits—no more, no less—ignore everything except the digits themselves. You can count the digits using:return value.match(/\d/g).length === 10;
This ensures the number contains precisely 10 digits, regardless of formatting, separators, or extra symbols. This approach is especially useful for normalizing numbers before storing or processing them, helping you catch sneaky formatting issues that regex alone might miss.
Use more specific patterns per country when validating local numbers.
Avoid allowing any character except digits, +, -, (, ), and spaces.
For global apps, test with a variety of international formats.
Consider integrating with libraries like libphonenumber for deeper validation (e.g., carrier detection, real-time feedback).
Use Cases
Signup Forms: Instantly validate user-entered phone numbers.
CRM Systems: Filter and clean phone numbers before adding to the database.
Marketing Automation: Ensure accurate numbers before sending SMS campaigns.
Booking Apps: Avoid invalid user entries in forms and call back flows.
While phone and email validation are probably the most common places you'll use regex, its real power shines through in a variety of situations. As you start coding more and more, regex becomes an indispensable tool—not just for form validation, but for extracting data from server logs, cleaning up messy JSON from API calls, and wrangling unstructured text in countless real-world scenarios. Think of it as your Swiss Army knife for data cleanup, pattern finding, and automation.
Combine with These Tools
JavaScript Regex Tester: Build or test custom phone number regex patterns.
Email Regex JavaScript Validator: Use with forms collecting both phone and email.
UUID Regex JavaScript Validator: Tag users by UUID after validating phone numbers.
Base64 Encoder: Securely encode validated phone numbers for storage or APIs.
Token Generator: Use in signup verification flows with OTP or SMS authentication
Whether you're tidying up user input or pulling structured information out of a tangle of raw data, regex is a skill that pays off across the board—especially when paired with the right supporting tools.
Frequently asked questions
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Phone Number Regex Javascript Validator
Search...
⌘K
Phone Number Regex Javascript Validator
Search...
⌘K


Phone Number Regex Javascript Validator
Phone Number Regex Javascript Validator
The Phone Number Regex JavaScript Validator lets you instantly check if a number string follows a valid phone number format using JavaScript regex. It’s ideal for use in contact forms, signup flows, or any web app that captures phone inputs. Use this alongside our JavaScript Regex Tester to build and refine your own patterns, or pair it with the Email Regex JavaScript Validator for complete contact form validation. You can also encode validated numbers using the Base64 Encoder or generate secure tokens for phone-based login systems with the Token Generator.
[A-Z]
: uppercase letters[a-z]
: lowercase letters[0-9]
: digits\.
: a literal dot+
: one or more of the preceding*
: zero or more of the preceding?
: optional (zero or one)^
: start of string$
: end of string
Test your APIs today!
Write in plain English — Qodex turns it into secure, ready-to-run tests.
Phone Number Regex Javascript Validator - Documentation
What is Phone Number Regex?
Phone number regex is a regular expression pattern that checks if a string matches a valid phone number format. The pattern can vary based on:
Country format
Mobile vs. landline
Use of symbols like +, -, (, ) or spaces
Phone Number Regex Pattern in JavaScript
Basic International Phone Number Regex:
/^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/
Pattern Breakdown:
^\+?
→ Optional + for country code[0-9]{1,4}?
→ Country code digits[-.\s]?
→ Optional separator(\(?\d{1,5}?\)?)
→ Optional area code with/without parentheses\d{1,5}
→ Prefix or number section\d{1,9}
→ Final part of the number$
→ End of string
When you're building forms to collect phone numbers—whether for contact, SMS notifications, or user profiles—users might enter numbers in a huge variety of ways. For example, all of the following are valid US-based numbers:
+1-202-555-0123
+44 20 7946 0958
(123) 456-7890
The use of throughout the pattern means any of these separator characters (hyphen, space, or dot) are permitted, or they may be omitted entirely. For example, both and will match, as will .
If you want to enforce consistent separators throughout the number (so users can’t mix, say, a space and a dash), you’d typically use a capturing group for the separator, like , and then reference it later in the pattern using a backreference like . This ensures that if a separator is used, it must be the same throughout. For instance, would match but would not. However, if you’d rather allow flexibility, omit the backreference and just repeat the separator sub-pattern as above—this is often more forgiving for real-world inputs.
Note: If you require strict format adherence, consider providing format hints to users on your form to guide their input and improve validation success.
This flexible pattern is a solid starting point for validating international and domestic phone numbers in a wide range of formats.
And that's just the tip of the iceberg! There are even more valid combinations out there, each with its own mix of separators, country codes, and spacing. Validating every possible variation by hand is a headache—but regex makes it simple and efficient to handle all these formats at once.
Code Example 1 – Basic Phone Number Validation
const phone = "+91-9876543210"; const pattern = /^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/; console.log(pattern.test(phone)); // true
Code Example 2 – Validate Multiple Numbers
const numbers = ["+1 800-123-4567", "1234567890", "(011) 2345 6789"]; const pattern = /^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/; numbers.forEach(num => { console.log(`${num} → ${pattern.test(num)}`); });
Covers a Wide Range of Formats
The regex pattern above is versatile enough to match a variety of phone number styles from around the world. Here are just a few examples of formats that this approach can validate:
International numbers with or without a plus:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+1 800-123-4567</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+44 20 7946 0958</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+31636363634</mark>
US and local formats:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">1234567890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">123-456-7890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">(123) 456-7890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">123.456.7890</mark>
Numbers with area codes in parentheses, with or without spaces:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+1 (415)-555-1212</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">(011) 2345 6789</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+1 (123)456-7890</mark>
Numbers with variable country codes and separators:
<mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+12 123-456-7890</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+123 075-63546725</mark>, <mark style="color: #272B32; border-width: 1px; border-radius: 4px; box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.1), 0px 1px 2px -1px rgba(0, 0, 0, 0.1); background-color: #E9D5FF; border-color: #C084FC;">+12(415)-555-1212</mark>
This pattern is flexible enough to handle:
Optional country codes (1 to 4 digits)
Area codes with or without parentheses
Dashes, spaces, or dots as separators
Numbers with up to 15 digits (including country and area codes)
So, whether you're working with North American, European, or other international phone numbers, this regex should have you covered for most common formats.
If you need even more granular control or support for additional country-specific patterns, consider refining the pattern further or stacking additional validation checks based on your application's needs.
Code Example 3 – Validate Input in a Web Form
<input type="text" id="phoneInput" placeholder="Enter your phone number" /> <p id="status"></p> <script> const pattern = /^\+?[0-9]{1,4}?[-.\s]?(\(?\d{1,5}?\)?)[-.\s]?\d{1,5}[-.\s]?\d{1,9}$/; document.getElementById("phoneInput").addEventListener("input", function () { const isValid = pattern.test(this.value.trim()); document.getElementById("status").textContent = isValid ? "✅ Valid Number" : "❌ Invalid Number"; }); </script>
Why Some Phone Numbers Fail Validation
If you’re wondering why something like (000) 999-5555 might not pass certain regex patterns, here’s what’s happening:
Some regexes require the separators between number groups—like spaces, dashes, or dots—to be consistent throughout the phone number. For example, if a pattern uses a capturing group for the first separator (like a space) and then references that captured character for the next separator, it expects all separators to match. So, a number using both a space and a dash (e.g., (000) 999-5555) would fail, because the separators aren’t the same.
To allow mixed separators (spaces, dashes, or dots in any combination), you’d typically adjust the pattern so each separator position is matched independently, instead of enforcing consistency via backreferences. This way, more phone number formats—including those with a mixture of symbols—will be considered valid.
How Backreferencing (\1
) Keeps phone number Separators Consistent
Regex patterns often use backreferences (like \1
) to enforce consistency within the matched string. In the context of phone numbers, suppose the separator—space, dash, or dot—can appear between sections: for example, "(123) 456-7890" or "123.456.7890".
Here's where backreferencing comes in handy:
([\-\s\.])?
captures an optional separator (dash, space, or dot) after your area code or number section.Later in the pattern, using
\1
tells the regex "the separator found earlier must be repeated here."
This means if there was a dash after the area code, only a dash can be used between the next number groups.
So, a string like "123-456-7890" matches because all separators are dashes. But "123-456.7890" wouldn't match since it switches from dash to dot—a consistency check courtesy of the backreference.
If you want to allow mixed separators, simply replace the specific backreference \1
with the broader pattern for any separator, but doing so opens the door to less standard formats.
Validating Only the Numeric Content
If you want to ensure a phone number contains exactly 10 digits—regardless of any spaces, dashes, parentheses, or formatting—it’s simple to filter out the non-numeric characters and check the result.
Here’s a quick way to do it in JavaScript:
const rawInput = "(123) 456-7890";
const digitsOnly = rawInput.replace(/\D/g, ""); // Remove non-digits
if (digitsOnly.length === 10) {
console.log("Valid 10-digit number");
} else {
console.log("Invalid number");
}
This method strips out everything except numeric characters, so formats like 123-456-7890
, (123) 456 7890
, or 1234567890
are all accepted as long as the actual digit count is ten.
You can easily use this approach to validate user input before storing, sending, or further processing the phone number in your application.
Digit Length Requirements by Country
When validating phone numbers, it’s important to account for country-specific digit requirements. Here’s a quick guide to the typical number of digits you’ll encounter in various regions:
Argentina: Expect either 8 to 13 digits in total, or formats split by a hyphen—3 to 6 digits, followed by 4 to 7 digits. If a country code is used (e.g., +54), its inclusion is mandatory, and the digits immediately follow.
United States: Standard phone numbers require at least 10 digits (not counting the country code). This covers both mobiles and landlines across the U.S. and Canada.
European Union: Many EU countries use 9 digits for local phone numbers, not including the country code or any leading zeroes.
India: Phone numbers comprise exactly 10 digits, usually paired with the +91 country code for international formats.
China: Numbers typically contain 10 or 11 digits. The country code (+86) precedes these in international formats.
Keep in mind, these rules serve as a baseline; always adjust your regex or validation logic based on the exact requirements for your users’ region.
Validating Phone Numbers With Country Codes Using ISD Lists
Need to ensure a phone number includes a valid country code? You can combine regex with an ISD code array to enhance validation—perfect for international signup forms or multi-region apps.
Here’s how it works:
Extract the digits from the input.
Check if the number is within a reasonable length (commonly, 8 to 16 digits).
Isolate the initial digits as a potential ISD (country) code.
Compare this code to a predefined list of valid ISD codes. If it matches, accept the number!
Example Approach:
const ISD_CODES = [
1, 44, 91, /* ...full ISD code list... */ 263
];
function validatePhoneWithISD(input) {
const digits = input.match(/\d+/g)?.join('') '';
if (digits.length < 8 digits.length > 16) return false;
const countryCodeLength = digits.length - 10; // Last 10 assumed as the main number
if (countryCodeLength > 0) {
const countryCode = parseInt(digits.slice(0, countryCodeLength), 10);
return ISD_CODES.includes(countryCode);
}
// No country code found, treat as local number
return true;
}
console.log(validatePhoneWithISD('91-9883208806')); // true
console.log(validatePhoneWithISD('1-800-1234567')); // true
console.log(validatePhoneWithISD('999123456')); // true (local, no ISD)
This approach lets you accept both local and international numbers, ensuring international users can’t slip in mistyped codes. For even tighter controls, throw in a regex pattern to capture proper separators. The ISD code match is what truly confirms the country code’s validity.
Handling Optional Country Codes and Separators
Sometimes phone numbers start with a country code like , which may or may not be followed by a dash or space (e.g., 1-800-123-4567, 1 800 123 4567, or just 800-123-4567). To handle these, regex grouping and optional quantifiers come in handy.
For example, if you want your regex to optionally match a leading (the US country code), possibly followed by a space or dash, you can use:
^(1[ -]?)
groups the and the potential separator together.
The after the group makes the entire (and the separator after it) optional.
Combining this with the rest of a standard US phone number pattern, you get:
/^(1[ -]?)?\d{3}[ -]?\d{3}[ -]?\d{4}$
This matches:
1-800-123-4567
1 800 123 4567
800-123-4567
These are commonly accepted by robust patterns for North American numbers, as well as many international regexes with country code support.
Making Groups Optional in Regex
Sometimes, you need to make a whole sequence of elements optional, not just a single character. For example, in North American phone number formats, it's common to allow an optional leading (the country code), sometimes followed by a space or hyphen. To accomplish this in regex, group the elements you want to make optional with parentheses and then add a after the group.
Example:
To match numbers that may or may not start with , followed by an optional space or hyphen, you’d use:
^(1[ -]?)?\d{3}[ -]?\d{3}[ -]?\d{4}$
Here’s what’s happening:
The group matches an optional , possibly followed by a space or hyphen. The entire group is optional thanks to the trailing .
The typical 10-digit phone number format, with optional separators.
Grouping and making parts of your pattern optional is key for flexible validation, especially for formats like phone numbers that vary by region or user input habits.
US Number Example Pattern Breakdown:
Optionally start with (with optional space or dash)
Area code
Optional separator
Prefix
Optional separator
Line number
By combining these strategies, your regex can flexibly match a wide variety of international and domestic phone number formats, handling optional country codes, spaces, dashes, and parentheses commonly found in real-world data.
Common Valid US Phone Number Formats
This regex is flexible enough to match a wide variety of real-world phone number formats, especially those commonly seen in the US. Here are some examples of valid US-based numbers it will accept:
202-515-5555
202 515 5555
(202)515 5555
1 202 515 5555
2025155555
1-202-515-5555
1202-515-5555
and more
Not accepted:
555-5555 (to accept, use a pattern that allows 7-digit numbers)
5555555 (same as above)
1 555)555-5555
123**&!!asdf#
(6505552368)
Numbers with leading digits not matching U.S. Standards, such as 2 (757) 622-7382 or 10 (757) 622-7382
Whether the number uses spaces, dashes, or parentheses, or includes a leading country code, this pattern adapts to most practical scenarios you'll encounter in web forms and user input.
What About Short Numbers?
If you need to accept formats like or (US 7-digit numbers), you’ll want to adjust your pattern accordingly. For example:
/^+?1?\s*?(?(\d{3})?(?:)[-\s])?\s*?\d{3}[-\s]?\d{4}$/
This regex will accept both 7- and 10-digit numbers with or without formatting.
Rejected Formats (for standard patterns):
or (unless you use a relaxed pattern as above)
(misplaced parenthesis)
(non-numeric, invalid symbols)
Numbers with too few or too many digits, or with misplaced separators, e.g., , ,
Overly long numbers like
Sample JavaScript Validation Function:
js function telephoneCheck(str) { var patt = new RegExp(/^+?1?\s*?(?\d{3}(?:)[-\s])?\s*?\d{3}[-\s]?\d{4}$/); return patt.test(str); } Test it with: js telephoneCheck("+1 555-555-5555"); // true
Final Thought:
Always balance thoroughness with user experience—accept all valid real-world inputs, but keep your regex as simple as possible for your use case. And remember, for complex, production-grade validation, a dedicated library can save you time and headaches.
How to Build a Generic Phone Number Validator That Ignores Non-Digit Characters
Want to validate a phone number regardless of its formatting—parentheses, dashes, or spaces? You can easily create a flexible JavaScript function that strips out everything except digits, then checks the length to match your country or app requirements.
Here’s a step-by-step approach:
Remove Non-Digit Characters:
UseString.prototype.replace()
with the/\D/g
regex to clear out anything that's not a digit.Count the Digits:
Once you have a string of pure digits, check if its length fits your desired range. For example, the US and Canada typically expect 10-digit numbers for local calls, while countries like India may have 10 or 11 digits with a country code.Parameterize for Flexibility:
You can make your function accept minimum and maximum digit counts for global compatibility.
function isValidPhoneNumber(input, minDigits = 10, maxDigits = 14) {
// Remove all non-digit characters
const digits = input.replace(/\D/g, "");
// Check if the digit count is within the expected range
return digits.length >= minDigits && digits.length <= maxDigits;
}
// Usage examples:
isValidPhoneNumber("+1 (800) 123-4567"); // true
isValidPhoneNumber("98765-43210", 10, 10); // true for Indian mobile numbers
isValidPhoneNumber("(011) 2345 6789", 10, 11); // true for larger range
Tips:
Adjust
minDigits
andmaxDigits
to support regional formats or enforce local rules.This method ensures user input is valid regardless of formatting quirks—spaces, dashes, or fancy parentheses are all ignored.
For more complex checks (like country-specific starting digits), combine this with regex or prefix validation.
Now you can confidently handle almost any phone number format users throw your way!
Validating Toll-Free Numbers (800, 900, etc.)
Need to single out special numbers like toll-free or premium-rate lines in the US (think 800, 888, 877, 866, or 900)? You can fine-tune your regex to specifically match these patterns.
Here's an example regex that matches common US toll-free and 900 numbers:
/^(?:\+?1[-.\s]?)?(?:800888877866855844833900)[-.\s]?\d{3}[-.\s]?\d{4}$/
This pattern covers:
Optional country code (+1)
Supported prefixes (800, 888, 877, 866, 855, 844, 833, 900)
Flexible separators (spaces, dashes, dots)
Standard 7-digit phone segment
Usage example:
const tollFreePattern = /^(?:\+?1[-.\s]?)?(?:800888877866855844833900)[-.\s]?\d{3}[-.\s]?\d{4}$/;
console.log(tollFreePattern.test("1-800-123-4567")); // true
console.log(tollFreePattern.test("(900) 555-0000")); // true
console.log(tollFreePattern.test("8881234567")); // true
Tip: Adjust the prefixes inside the pattern as needed for your region, or combine this with your general validator to catch and handle special number categories in your forms and backend systems.
Validating and Formatting Phone Numbers Without Double Spaces or Hyphens
When it comes to phone number validation, especially for international formats, your regex needs to be flexible—but not too permissive. A robust pattern should accept variations with country codes, area codes (sometimes in parentheses), and allow for separators like spaces or hyphens, all while eliminating common issues such as double spaces or consecutive hyphens.
Sample Regex for Flexible Phone Numbers
Here’s an improved pattern that captures a wide range of phone number formats and prevents double spaces or hyphens:
const phonePattern = /^(\+?\d{1,4}[\s-]?)?(\(?\d{1,5}\)?[\s-]?)?(\d{1,5}[\s-]?){1,4}\d{1,9}$/;
Enforcing Clean Formatting
To ensure you don’t accept numbers with double spaces or double hyphens, you can run a quick check alongside your main validation:
function hasNoDoubleSeparators(num) {
return !(/[\s-]{2,}/.test(num));
}
Combine it with your validation logic:
function isValidPhoneNumber(phoneNumber) {
return phonePattern.test(phoneNumber) && hasNoDoubleSeparators(phoneNumber);
}
What This Covers
This approach will validate numbers like:
+44 07988-825 465
+44 (0) 7988-825 465
123 456-789 0123
123-123 123
123 123456
1234567890
Bonus: It won’t allow double spaces or hyphens anywhere in the phone number, ensuring cleaner, more standardized input for your database, forms, or APIs.
Feel free to tweak the pattern for your country-specific requirements!
Ensuring Regex Adheres to NANP Rules
If you want your phone number regex to strictly follow North American Numbering Plan (NANP) formatting, you’ll need to tighten up the validation logic—basic digit matching is only half the story.
Key NANP Requirements
Area Code and Exchange Format:
Both the area code and the exchange (the next three digits) must begin with a digit from 2–9, not 0 or 1.N11 Restriction:
Standard area codes and exchanges can’t end in “11” (to avoid overlap with service numbers), with exceptions for toll-free and premium area codes like 800 or 900.Structure:
The learned format isNXX-NXX-XXXX
, whereN
= [2–9] andX
= [0–9].Country Code +1:
For international compatibility, start the regex with+1
(optionally), along with common separator support.
Recommended Regex Pattern
For stricter NANP compliance, here’s an improved version:
/^\+1[-.\s]?([2-9][0-9]{2})[-.\s]?([2-9][0-9]{2})[-.\s]?([0-9]{4})$/
[2-9][0-9]{2}
ensures area and exchange codes start with 2–9.Separators
[-.\s]?
match dashes, dots, or spaces.Supports an optional “+1” prefix.
[-.\s]?
is part of the pattern matches any one of the separator characters—dash (), dot (), or whitespace ()—and makes it optional. In other words, it allows for phone numbers to be written with or without separators between number groups.
For example, , , or would all match, as well as . This flexibility is achieved because the makes the separator optional.
If you want to ensure consistency in separators (so the same character is used throughout the number), you can use a capturing group and backreference:
captures an optional separator.
matches three digits.
reuses the captured separator, requiring it to be the same for each segment.
With this approach, a number like (using both a space and a dash) would not validate, as the separators differ. If you prefer to accept mixed separators or nonstandard formats, you can simply remove the backreference () and keep the separator sub-pattern.
Regardless of the approach you take, consider providing a format hint to users so their input matches your expectations.
Important Considerations
International Numbers:
This regex strictly enforces North American formats. For global support, consider using libraries like libphonenumber (https://github.com/google/libphonenumber) that specialize in international phone validation.Server-Side Validation:
Regex validation in the browser helps users catch errors early, but always revalidate phone numbers securely on your backend.
By adjusting your pattern as above, you’re far more likely to reject invalid NANP numbers and accept only those that truly fit the regional rules.
Strict vs. Loose Phone Number Validation in JavaScript
When validating phone numbers with JavaScript regex, the level of strictness can make a big difference in user experience and accuracy.
Loose validation is forgiving—it accepts a wide variety of phone number formats. This means users can enter their numbers with different separators (dashes, spaces, dots), parentheses, or even with or without a country code. Examples of inputs a loose regex might permit include:
(123) 456-7890
+31636363634
123-456-7890
123.456.7890
The main advantage? Users don't get blocked by formatting requirements they may not expect. Especially in forms like registrations, this reduces friction and form abandonment. The trade-off is that loose patterns won't catch typos or malformed numbers—for example, they may accept too few or too many digits.
Strict validation, on the other hand, enforces a precise expected format. These regex patterns will only match well-defined phone number styles: requiring specific lengths, country codes, or exact arrangements of separators and digits. If you want to guarantee clean, predictable data—for example, before storing numbers in a database or for integrations with services like Twilio—strict validation is the safer bet. However, users might find it restrictive if they aren't sure of the expected input style.
In practice:
Use loose validation when you want to cast a wide net and are ready to clean or format numbers after submission.
Use strict validation if downstream processes (like SMS verification) require consistently formatted numbers.
Most developers find a balance—allow flexible input, but normalize and validate further before saving or processing. Consider your audience, the importance of data quality, and your backend requirements when choosing between strict and loose validation approaches.
Tips for Flexible and Reliable Phone Validation
Rather than getting stuck on specific formats, consider validating the numeric content directly. For example, you can strip out all non-digit characters and check if the result matches standard North American numbering:
var originalPhoneNumber = "415-555-1212"; function isValid(p) { var phoneRe = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/; var digits = p.replace(/\D/g, ""); return phoneRe.test(digits); }
If you need to support custom or evolving formats, try building your regular expression from a clear template string. This makes it easy to add new patterns—whether you're a developer or simply updating options in a settings page:
var formats = "(999)999-9999999-999-99999999999999"; var r = RegExp("^(" + formats .replace(/([()])/g, "\$1") .replace(/9/g,"\d") + ")$" );
This approach keeps your validation logic both transparent and easy to maintain, letting you adapt as your needs change.
Pro Tips
Always .trim() input to remove accidental whitespace from the user.
If you only need Indian mobile numbers, simplify the regex to:
/^[6-9]\d{9}$/
Strictly need 10 digits?
If your use case requires exactly 10 digits—no more, no less—ignore everything except the digits themselves. You can count the digits using:return value.match(/\d/g).length === 10;
This ensures the number contains precisely 10 digits, regardless of formatting, separators, or extra symbols. This approach is especially useful for normalizing numbers before storing or processing them, helping you catch sneaky formatting issues that regex alone might miss.
Use more specific patterns per country when validating local numbers.
Avoid allowing any character except digits, +, -, (, ), and spaces.
For global apps, test with a variety of international formats.
Consider integrating with libraries like libphonenumber for deeper validation (e.g., carrier detection, real-time feedback).
Use Cases
Signup Forms: Instantly validate user-entered phone numbers.
CRM Systems: Filter and clean phone numbers before adding to the database.
Marketing Automation: Ensure accurate numbers before sending SMS campaigns.
Booking Apps: Avoid invalid user entries in forms and call back flows.
While phone and email validation are probably the most common places you'll use regex, its real power shines through in a variety of situations. As you start coding more and more, regex becomes an indispensable tool—not just for form validation, but for extracting data from server logs, cleaning up messy JSON from API calls, and wrangling unstructured text in countless real-world scenarios. Think of it as your Swiss Army knife for data cleanup, pattern finding, and automation.
Combine with These Tools
JavaScript Regex Tester: Build or test custom phone number regex patterns.
Email Regex JavaScript Validator: Use with forms collecting both phone and email.
UUID Regex JavaScript Validator: Tag users by UUID after validating phone numbers.
Base64 Encoder: Securely encode validated phone numbers for storage or APIs.
Token Generator: Use in signup verification flows with OTP or SMS authentication
Whether you're tidying up user input or pulling structured information out of a tangle of raw data, regex is a skill that pays off across the board—especially when paired with the right supporting tools.
Frequently asked questions
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex
Discover, Test, and Secure your APIs — 10x Faster.

Product
All Rights Reserved.
Copyright © 2025 Qodex