regex for valid phone number with code examples

Regular expressions, commonly known as regex, are a powerful tool for working with text data. They allow developers to specify a pattern of characters to match, search, and transform strings based on that pattern. One common use case for regular expressions is validating and working with phone numbers. In this article, we will explore regex patterns for validating phone numbers and provide code examples in different programming languages.

Before diving into regex patterns, it is essential to understand some basics of phone numbers' syntax. A standard phone number consists of three parts – the country code, the area code, and the local number. The country code is a two-letter or three-digit code that identifies the country the phone number belongs to. The area code is a three-digit code that identifies the region or city within a country, whereas a local number is typically a seven or eight-digit number that identifies a specific phone line.

With this basic understanding, let us explore some regex patterns for validating phone numbers.

  1. Regex Pattern for Validating a US Phone Number

A typical US phone number looks like this – (123) 456-7890. To validate this phone number pattern using regex, we can use the following code in JavaScript:

const usPhoneRegex = /^\(?([0-9]{3})\)?[- ]?([0-9]{3})[- ]?([0-9]{4})$/;
const phoneNumber = '(123) 456-7890';

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

In this code snippet, we define a regex pattern to match a US phone number. The pattern starts with ^, which matches the beginning of the string, followed by an optional open parenthesis \(?\. We add a ? after the open parenthesis to indicate that it is optional.

([0-9]{3}) matches three consecutive digits and groups them together in the first capture group. Similarly, ([0-9]{3}) and ([0-9]{4}) matches the area code and the local number, respectively, and groups them in separate capture groups.

The [- ]? matches an optional space or hyphen between the groups. Finally, we finish the pattern with $, which matches the end of the string.

  1. Regex Pattern for Validating an International Phone Number

An international phone number includes the country code as the first part of the phone number. For example, a typical UK phone number looks like this – +44 7911 123456. To validate international phone numbers using regex, we can use the following code in JavaScript:

const intlPhoneRegex = /^\+(?:[0-9] ?){6,14}[0-9]$/;
const phoneNumber = '+44 7911 123456';

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

In this regex pattern, we start with ^, which matches the beginning of the string. The ^\+ matches the plus sign, which is mandatory for all international phone numbers. We then group the country code and the following digits together using (?:[0-9] ?). This group can occur between six and fourteen times using {6,14}.

The final [0-9]$ pattern matches the last digit of the phone number and ensures that the string ends with a digit. This pattern allows for international phone numbers with or without spaces between the digits.

  1. Regex Pattern for Validating a Phone Number with Extensions

Some phone numbers may include an extension at the end, such as (123) 456-7890 ext. 1234. To validate a phone number with an extension, we can use the following regex pattern in JavaScript:

const phoneRegexExt = /^\+?\d{0,3}[\- ]?\(?\d{3}\)?[\- ]?\d{3}[\- ]?\d{4}[\- ]*((ext\. |x)\d{1,5})?$/i;
const phoneNumber = '(123) 456-7890 ext. 1234';

if (phoneRegexExt.test(phoneNumber)) {
  console.log('Valid phone number with extension');
} else {
  console.log('Invalid phone number with extension');
}

In this pattern, we start with ^\+?\d{0,3}, which matches an optional plus sign and up to three digits for the country code. We then allow for optional hyphens or spaces using [\- ]?. The area code is enclosed in optional parentheses using \(?\d{3}\)?[\- ]?.

Following the area code, we match the seven-digit local number using \d{3}[\- ]?\d{4}[\- ]*. We allow for an extension to follow, enclosed in (ext\. |x)\d{1,5}.

This pattern uses the i flag to make the pattern case insensitive so that it can match variations of 'ext.' or 'EXT.'

  1. Regex Pattern for Validating a Phone Number without Formatting

For some applications, you may need to validate phone numbers that are not formatted. For example, a user may enter a phone number as 1234567890. In these cases, you can use the following regex pattern in JavaScript:

const phoneRegexPlain = /^(\+1)?[2-9]\d{9}$/;
const phoneNumber = '1234567890';

if (phoneRegexPlain.test(phoneNumber)) {
  console.log('Valid phone number without formatting');
} else {
  console.log('Invalid phone number without formatting');
}

In this pattern, we start with ^(\+1)?, which matches an optional US country code. We then match the area code and the seven-digit local number using [2-9]\d{9}. This pattern ensures that the phone number is a valid US phone number without formatting.

Conclusion

In this article, we explored regex patterns for validating phone numbers. We looked at patterns for US and international phone numbers, phone numbers with extensions, and phone numbers without formatting. These patterns can be used in various programming languages and can be customized to fit specific use cases. When working with phone numbers, it is essential to validate them to ensure that they are in the correct format, consistent, and accurate. With the power of regex, validating phone numbers becomes an easy and efficient process.

In addition to the regex patterns discussed in the previous article, there are other variations and modifications that can be used to validate phone numbers based on specific requirements. Let's look at some more examples.

  1. Regex Pattern for Validating Phone Numbers with Country Codes

If you need to validate phone numbers with specific country codes, you can modify the regex pattern to match those codes. For example, if you want to validate phone numbers from the UK, you can use the following regex pattern in JavaScript:

const ukPhoneRegex = /^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/;
const phoneNumber = '07911 123456';

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

In this pattern, we start with ^(\+44\s?7\d{3}|\(?07\d{3}\)?), which matches either a plus sign followed by 44 and a 7-digit mobile code, or an optional open parenthesis, a 0, a 7-digit mobile code, and closing parenthesis. We then match two optional spaces using \s? and continue with the 3-digit and 4-digit blocks using \d{3}\s?\d{3}.

This pattern is specific to validating UK mobile phone numbers.

  1. Regex Pattern for Validating Phone Numbers with Specific Area Codes

If you need to validate phone numbers for specific area codes, you can modify the regex pattern to match those codes. For example, if you want to validate phone numbers from the New York City area code (212), you can use the following regex pattern in JavaScript:

const nycPhoneRegex = /^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$/;
const phoneNumber = '(212) 555-1212';

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

In this pattern, we start with ^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$, which matches an optional open parenthesis followed by a 3-digit area code, followed by an optional close parenthesis. We allow for hyphens or spaces between the groups of digits and make sure that the phone number ends with a 4-digit local number.

This pattern is specific to validating phone numbers for the 212 area code in New York City.

Conclusion

Validating phone numbers can be a complex process, but with the use of regular expressions, developers have a powerful tool to make the process easier. By using regex patterns, we can ensure that phone numbers are in the correct format and meet specific requirements. As we have seen in this article, regex patterns can be modified to meet the needs of different applications, including validating specific country codes and area codes. Whether you are working with US phone numbers, international phone numbers, or customized requirements, using regex patterns ensures that phone numbers are accurately and efficiently validated.

Popular questions

Q1. What is regex?

A1. Regex, or regular expression, is a sequence of characters used to define search patterns and manipulate text. It is a powerful tool for working with text data and can be used in various programming languages.

Q2. Why is it important to validate phone numbers using regex patterns?

A2. Validating phone numbers using regex patterns ensures that they are in the correct format and meet specific requirements. This helps maintain data consistency and accuracy, and ensures that phone numbers can be used for their intended purposes.

Q3. What is a standard phone number format?

A3. A standard phone number consists of three parts – the country code, the area code, and the local number. The country code is a two-letter or three-digit code that identifies the country the phone number belongs to. The area code is a three-digit code that identifies the region or city within a country, whereas a local number is typically a seven or eight-digit number that identifies a specific phone line.

Q4. Can regex patterns be modified to validate phone numbers with specific requirements?

A4. Yes, regex patterns can be modified to meet the needs of different applications, including validating specific country codes and area codes. This ensures that phone numbers are accurately and efficiently validated.

Q5. What are some examples of customized regex patterns for phone number validation?

A5. Examples of customized regex patterns for phone number validation include patterns for validating US phone numbers, international phone numbers, phone numbers with extensions, phone numbers without formatting, and phone numbers with specific country codes or area codes.

Tag

PhoneRegEx

As a senior DevOps Engineer, I possess extensive experience in cloud-native technologies. With my knowledge of the latest DevOps tools and technologies, I can assist your organization in growing and thriving. I am passionate about learning about modern technologies on a daily basis. My area of expertise includes, but is not limited to, Linux, Solaris, and Windows Servers, as well as Docker, K8s (AKS), Jenkins, Azure DevOps, AWS, Azure, Git, GitHub, Terraform, Ansible, Prometheus, Grafana, and Bash.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top