Phone Number Validation in JavaScript Using Regex

Are you excited to explorephone number validation in JavaScript?

Ensuring phone numbers is important in every aspect.

In this article, we’ll explain how to validate phone numbers straightforwardly using JavaScript and HTML.

Read on to learn the simplest method to validate phone numbers in JavaScript using Regular Expressions.

Validating phone numbers using regex in JavaScript

There are several ways to validate phone numbers using JavaScript. One common method is to use a regular expression (regex) to check if the input matches a specific pattern.

Below is the JavaScript Regex code you’ll need to validate phone numbers.

/^(?(\d{3}))?[- ]?(\d{3})[- ]?(\d{4})$/

Let’s break this down to help you understand it more easily:

/^(?

The number can begin with an open parenthesis.

(\d{3})

For the format to be valid, you need to type three numbers. If there’s no parenthesis, those numbers should be at the beginning.

)?

You can add a closing parenthesis with it.

[- ]?

The string can have a hyphen if you want. You can put it after the parenthesis or after the first three digits. For example, you can write it as (143)- or 143-.

(\d{3})

After that, you need to have three more digits in the number. It can be like this: (123)-456, 123-456, or 123456.

[- ]?

You can add a hyphen at the end if you want, like this: (123)-456-, -123-, or 123456-.

(\d{4})$/

Lastly, the series should finish with four numbers.

How to validate a phone number in JavaScript?

As we mentioned earlier you can validate phone number using regex in JavaScript.

Here’s an example of a function that uses a regex to validate phone numbers in the format (123) 456-7890, (123)456-7890, 123-456-7890, or 1234567890:

function validatePhoneNumber(input_str) {
 var re = /^\\(?(\d{3})\\)?[- ]?(\d{3})[- ]?(\d{4})$/;
 return re.test(input_str);
}

You can also use HTML5 form validation to validate phone numbers.

Here’s an example of an HTML form that uses the pattern attribute to specify a regex for validating phone numbers:

<form>
 <label for="phone">Phone:</label>
 <input type="tel" id="phone" name="phone" pattern="\\d{3}[ -]?\\d{3}[ -]?\\d{4}" required>
 <input type="submit">
</form>

In our given example, the pattern attribute specifies a regex that checks for three digits, followed by an optional hyphen or space, three more digits, another optional hyphen or space, and finally four digits.

The required attribute specifies that the phone number field is required.

Here’s the complete example code:

<!DOCTYPE html>
<html>
<head>
 <title>Phone Number Validation Form</title>

 <h2>How to validate a phone number in JavaScript using Regex?</h2>

 <script type="text/javascript">
 function validatePhoneNumber() {
 var phoneNumber = document.getElementById("phone").value;
 var regex = /^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$/; 
 if (regex.test(phoneNumber)) {
 alert("The phone number is valid.");
 } else {
 alert("The phone number is not valid.");
 }
 }
 </script>

</head>
<body>
 <form onsubmit="event.preventDefault(); validatePhoneNumber();">
 <label for="phone">Phone:</label>
 <input type="tel" id="phone" name="phone" required>
 <input type="submit">
 </form>
</body>
</html>

As you can see, we used the regular expression^(?\d{3})?[- ]?\d{3}[- ]?\d{4}$checks for an optional opening parenthesis, followed by three digits, an optional closing parenthesis, an optional hyphen or space, three more digits, another optional hyphen or space, and finally four digits.

Please note that this code will only work if JavaScript is enabled in the user’s browser. Also, this is a very basic form and does not include any server-side processing or error handling.

Output:

Here’s another example code using the regular expression ^(09|+639)\d{9}$ checks for exactly 11 digits. The phone number should start with 09 or +639.

<!DOCTYPE html>
<html>
<head>

 <title>Phone Number Validation Form</title>

 <h2>How to validate a phone number in JavaScript using Regex?</h2>
 <script type="text/javascript">
 function validatePhoneNumber() {
 var phoneNumber = document.getElementById("phone").value;
 var regex = /^(09|\+639)\d{9}$/;
 if (regex.test(phoneNumber)) {
 alert("The phone number is valid.");
 } else {
 alert("The phone number is not valid.");
 }
 }
 </script>
</head>
<body>
 <form onsubmit="event.preventDefault(); validatePhoneNumber();">
 <label for="phone">Phone:</label>
 <input type="tel" id="phone" name="phone" required>
 <input type="submit">
 </form>
</body>
</html>

Output:

Different phone number regex patterns for 2026

Phone numbers come in many shapes. I always tell BSIT students working on their capstone forms: there is no single regex that catches every phone format on Earth. Instead, pick the pattern that matches your target users. Here are the three patterns I reach for most often.

1. Basic US phone number format

This one accepts numbers written as (123) 456-7890, 123-456-7890, or 1234567890. Good starter regex for a Philippine or American user base.

const phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

console.log(phoneRegex.test("(123) 456-7890"));  // true
console.log(phoneRegex.test("123-456-7890"));    // true
console.log(phoneRegex.test("1234567890"));      // true
console.log(phoneRegex.test("12-34-567890"));    // false

2. International format with country code

If your form accepts users from multiple countries, you need a pattern that allows an optional plus sign, an optional country code, and flexible separators. This is the one I use for most capstone contact forms.

const intlPhoneRegex = /^\+?([0-9]{1,3})?[-. ]?\(?([0-9]{1,4})\)?[-. ]?([0-9]{1,4})[-. ]?([0-9]{1,9})$/;

console.log(intlPhoneRegex.test("+63 917 123 4567"));  // true (Philippines)
console.log(intlPhoneRegex.test("+1-555-123-4567"));   // true (US)
console.log(intlPhoneRegex.test("+44 20 7946 0958"));  // true (UK)
console.log(intlPhoneRegex.test("917-123-4567"));      // true (no country code)

3. Strict E.164 format

E.164 is the international phone number standard used by SMS gateways, WhatsApp Business API, and Twilio. It looks like +639171234567 with no spaces or dashes, max 15 digits after the plus. Use this pattern when you plan to send SMS or integrate with a phone-based service.

const e164Regex = /^\+[1-9]\d{1,14}$/;

console.log(e164Regex.test("+639171234567"));  // true
console.log(e164Regex.test("+15551234567"));   // true
console.log(e164Regex.test("+0123456"));       // false (starts with 0)
console.log(e164Regex.test("639171234567"));   // false (missing +)

How the phone number regex actually works

New JavaScript developers often copy a regex from Stack Overflow without knowing what each symbol does. That is a mistake. When your form starts rejecting valid phone numbers, you cannot fix what you cannot read. Here is the international pattern broken down piece by piece.

/^\+?([0-9]{1,3})?[-. ]?\(?([0-9]{1,4})\)?[-. ]?([0-9]{1,4})[-. ]?([0-9]{1,9})$/

^          Start of string (nothing before the phone number)
\+?        Optional plus sign
([0-9]{1,3})?  Optional country code, 1 to 3 digits
[-. ]?     Optional separator: dash, dot, or space
\(?        Optional opening parenthesis
([0-9]{1,4})   1 to 4 digits (area code)
\)?        Optional closing parenthesis
[-. ]?     Optional separator
([0-9]{1,4})   1 to 4 digits (first block)
[-. ]?     Optional separator
([0-9]{1,9})   1 to 9 digits (final block)
$          End of string

The ^ and $ anchors are critical. Without them, the regex would match a valid phone number embedded inside garbage input like “call me at 123-456-7890 haha”, which is not what you want in a form validator.

Real-world example: HTML form with phone number validation

Here is a complete working example. The form accepts a phone number, validates it on submit, and shows an inline error message if the input is wrong. I use this exact pattern in my capstone project templates for BSIT students building contact forms and user registration pages.

<form id="contactForm">
  <label for="phone">Phone Number</label>
  <input type="tel" id="phone" name="phone" required>
  <span id="phoneError" style="color:red;display:none;">
    Please enter a valid phone number.
  </span>
  <button type="submit">Submit</button>
</form>

<script>
document.getElementById("contactForm").addEventListener("submit", function(e) {
  e.preventDefault();

  const phoneInput = document.getElementById("phone");
  const errorEl = document.getElementById("phoneError");
  const phoneRegex = /^\+?([0-9]{1,3})?[-. ]?\(?([0-9]{1,4})\)?[-. ]?([0-9]{1,4})[-. ]?([0-9]{1,9})$/;

  if (!phoneRegex.test(phoneInput.value)) {
    errorEl.style.display = "inline";
    phoneInput.focus();
    return false;
  }

  errorEl.style.display = "none";
  console.log("Phone number is valid:", phoneInput.value);
  // Continue with form submission logic
});
</script>

Notice I used type="tel" on the input. This tells mobile browsers to show the numeric keypad, which improves usability on phones. The HTML5 validation alone is not enough because it accepts almost anything as valid, so we still need the regex check in JavaScript.

Common phone number regex mistakes to avoid

I have reviewed hundreds of capstone forms over the years. These are the five phone validation mistakes I see most often. Fix these and your form will handle real-world phone numbers correctly.

  • Forgetting the anchors. Without ^ and $, your regex matches partial phone numbers inside garbage text. Every phone validator should be anchored.
  • Hardcoding only one country format. If your regex accepts only (XXX) XXX-XXXX, users from the Philippines with numbers like 09171234567 get rejected. Support at least the international pattern.
  • Treating regex as the only defense. Regex checks format but not authenticity. For real SMS-based verification, send a one-time code to the number. Regex is your first filter, not your last check.
  • Not escaping special characters. The plus sign and parentheses in regex have meaning. If you forget the backslash on \+, \(, or \), the pattern will not match what you expect.
  • Rejecting valid formats due to spacing. Users type phone numbers with dashes, dots, spaces, or nothing at all. Your regex should accept all reasonable separators using [-. ]?, not force a single format.

By the way, if you are handling a lot of international phone numbers, consider using Google’s libphonenumber library instead of pure regex. Regex validates format, but libphonenumber validates real number ranges, country codes, and carrier prefixes. For a simple contact form, pure regex is enough. For a production app that sends SMS or verifies users, use the library.

Official documentation

Conclusion

In conclusion, this article has exploredhow to validate phone numbers in JavaScript using Regular Expressions (regex).

We’ve covered the essential regex patterns for validating various phone number formats, explained the code breakdown, and offered practical examples for implementing phone number validation in both JavaScript functions and HTML forms.

It’s important to remember that the code examples provided here are basic and serve as a starting point for implementing phone number validation in your web applications.

We hope this article has provided you with enough information to understand phone number validation in JavaScript and implement it effectively in your projects.

If you want to explore more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders .

Frequently Asked Questions

What is the simplest regex for validating phone numbers in JavaScript?
For basic US-style phone numbers, the simplest regex is /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/ which accepts formats like (123) 456-7890, (123)456-7890, 123-456-7890, and 1234567890. Use it with String.prototype.test() like this: regex.test(input). If you need international support, consider using a library like libphonenumber-js instead of a custom regex.
How do I validate Philippine mobile phone numbers (09xx) in JavaScript?
For PH mobile numbers, use the regex /^(09|\+639)\d{9}$/ which matches 11 digits starting with 09 (local format like 09171234567) or +639 followed by 9 digits (international format like +639171234567). PH mobile prefixes include 0905, 0917, 0918, 0926, 0927, 0928, 0935, 0936, 0937, 0939, 0945, 0946, 0947, 0948, 0949, 0951, 0961, 0966, 0967, 0975, 0977, 0995, 0996, 0997. For stricter validation, you can encode the valid prefixes into the regex itself.
What is the difference between using a JavaScript regex and the HTML5 pattern attribute?
The HTML5 pattern attribute runs validation in the browser automatically when the form is submitted (no JavaScript code required). Example: pattern=”\d{3}[ -]?\d{3}[ -]?\d{4}”. A JavaScript regex gives you more control, lets you validate in real time as the user types, and lets you show custom error messages. For simple cases, the HTML5 pattern is fine. For complex requirements or live feedback, use a JavaScript regex with addEventListener(‘input’).
Why is my phone regex matching invalid numbers?
The most common reason is forgetting the ^ (start) and $ (end) anchors. Without them, your regex will match a valid phone number embedded inside any longer string. Always wrap your regex like /^…$/. Another common bug is using \d* (zero or more) instead of \d{3} (exactly three). Test your regex on edge cases like empty string, very long strings, letters, special characters, and only digits.
How do I allow the + country code prefix in the regex?
Use the pattern /^\+?(\d{1,3})?[- ]?\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/ which accepts an optional + sign, an optional 1-3 digit country code, and the standard phone format. For example, this matches +1 (123) 456-7890, +63 917 123 4567, and 123-456-7890. Remember to escape the + sign as \+ in your regex pattern.
Should I use libphonenumber instead of a regex for phone validation?
For production applications, yes. The libphonenumber-js library (a JavaScript port of Google’s libphonenumber) handles all international phone number formats, area codes, mobile vs landline detection, and formatting. Install it with npm install libphonenumber-js and use it like: import { isValidPhoneNumber } from ‘libphonenumber-js’; isValidPhoneNumber(‘+639171234567’). A custom regex is fine for simple cases, but libphonenumber catches edge cases your regex will miss.
What is E.164 international phone number format?
E.164 is the international telephone numbering standard maintained by ITU-T. The format is a + sign followed by 1 to 15 digits with no spaces, parentheses, or hyphens. Examples: +14155551234 (US), +639171234567 (PH), +447911123456 (UK). A simple E.164 regex is /^\+[1-9]\d{1,14}$/. E.164 is required by many SMS APIs (Twilio, Semaphore, Vonage) so storing all phone numbers in E.164 format is best practice.
How do I show a custom error message when phone validation fails?
Combine the regex test with a DOM update. Get a reference to an error element with document.getElementById(‘error’), then in your validation function: if (regex.test(input)) errorEl.textContent = ”; else errorEl.textContent = ‘Please enter a valid phone number like 09171234567’. For HTML5 forms, use the title attribute on the input to show the browser’s default tooltip on invalid input.
Can I validate a phone number on input change instead of on submit?
Yes. Use addEventListener(‘input’, handler) on the input element. The handler runs every keystroke. Example: phoneInput.addEventListener(‘input’, function() { errorEl.style.display = regex.test(this.value) ? ‘none’ : ‘block’; }). This gives instant feedback. To avoid annoying users with red errors while they’re still typing, only show the error after they leave the field (use ‘blur’ instead of ‘input’).
Does the regex pattern work the same in Node.js and the browser?
Yes. JavaScript regex syntax is identical in Node.js and all modern browsers (Chrome, Firefox, Safari, Edge). The RegExp object and string methods like .test(), .match(), and .replace() behave the same in both environments. The only differences are in features like lookbehind (added in Chrome 62+, Node 10+) and named capture groups (added in Chrome 64+, Node 10+). For phone validation, basic regex syntax works everywhere.

We are hoping that this article helps you validate phone numbers in JavaScript more confidently. If you have any questions or suggestions about phone number regex in JavaScript, please feel free to drop them in the comments below or contact us at our contact page.

Caren Bautista

Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel  · View all posts by Caren Bautista →

Leave a Comment