javascript regex check phone number

How to Check Phone Number Using JavaScript Regex

As a web developer, it's important to validate user inputs before sending them to the server. One of the most common inputs is the phone number field. In this article, I'll show you how to use JavaScript regex to validate phone numbers.

The Regex Pattern

First, let's take a look at the regex pattern we'll be using:


const phoneRegex = /^\d{10}$/;

This regex pattern matches a 10-digit phone number that contains only numbers.

Explanation of the Regex Pattern

  • ^ - matches the beginning of the input string
  • \d - matches any digit (0-9)
  • {10} - specifies that the previous character should appear exactly 10 times
  • $ - matches the end of the input string

Code Example

Now, let's see how we can use this regex pattern in JavaScript:


const phoneNumber = '1234567890';
const phoneRegex = /^\d{10}$/;

if (phoneRegex.test(phoneNumber)) {
  console.log('Valid phone number!');
} else {
  console.log('Invalid phone number!');
}

In this example, we're testing whether the phone number is valid using the test() method. If the phone number matches the regex pattern, we'll log "Valid phone number!" to the console. Otherwise, we'll log "Invalid phone number!".

Alternative Regex Patterns

There are many different ways to validate phone numbers using regex. Here are a few alternative patterns:


// Matches a 10-digit phone number with or without dashes
const phoneRegex1 = /^\d{3}-?\d{3}-?\d{4}$/;

// Matches a 10-digit phone number with or without parentheses and dashes
const phoneRegex2 = /^1?\(?\d{3}\)?-?\d{3}-?\d{4}$/;

Feel free to choose the regex pattern that best fits your needs!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe