Skip to content

Regular expression for US and Canada phone number

·3 min read

Regular Expressions

Regular Expressions (Photo credit: Jeff Kubina)

This a quick post regarding how to validate US and Canada [phone number] (Note: The original article is no longer available online) in very possible formats.

Requirements:

To determine whether a user entered a North American phone number in a common format, including the local area code. The supported formats are 1234567890, 123-456-7890, 123.456.7890,  123 456 7890, (123) 456 7890, and all related combinations. If the phone number is valid, we will convert that our standard format,  (123) 456-7890, so that the phone number records are consistently recorded.

Suggested expression: ^\(?([0-9])\)?[-. ]?([0-9])[-. ]?([0-9])$

Valid phone number series for the expression:

  • 123-456-7890
  • 123 456-7890
  • 123-456 7890
  • (123)-456-7890
  • 123 456 7890

 

.NET C# Code Snippet

string userInput = txtPhoneNumber.Text;
 
Regex regexPhoneNumber = new Regex(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
 
if (regexPhoneNumber.IsMatch(userInput))
{
	string formattedPhoneNumber = regexPhoneNumber.Replace(userInput, "($1) $2-$3");
}
else
{
	// Invalid phone number
}

The following layout breaks the [regular expression] (Note: The original article is no longer available online) into its individual parts, excluding the repeating groups of digits:

^Assert position at the beginning of the string.
\(Match a literal "("
  ?between zero and one time.
(Capture the enclosed match to back reference 1
  [0-9]Match a digit
exactly three times.
)End capturing group 1.
\)Match a literal ")"
?between zero and one time.
[-. ]Match one character from the set "-. "
?between zero and one time.
?[Match the remaining digits and separator.]
$Assert position at the end of the string.

Here, '^' and '$' are meta-characters named an anchor or assertion. '^ is used to mask the start of regular expression and $ is used to mark the end. '$' is used to stop matching too much string into final result than required.

 

For people seeking more information regarding the expression are suggested to visit detailed post here: http://blog.stevenlevithan.com/archives/validate-phone-number

Related articles

Post image