Skip to content
the poor coder

javascript regex check phone number

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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:

Text

// 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!

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC