Dart regex to validate US/CA phone numbers

Last updated on November 19, 2020 A Goodman Loading... Post a comment

Validating phone numbers is a common task when making Flutter applications. Before sending an SMS with a verification code (that usually costs real money), we should implement some basic checks.

In this article, we’ll use a regular expression pattern to validate the United States and Canada phone numbers that match the following formats:

(123) 456 789
321-123-4567
+01 (123) 456 7890
+1 123 456 7890
123 456 7890

The phone regex pattern

Here’s the phone regex pattern used in our Dart code:

^(\+0?1\s)?((\d{3})|(\(\d{3}\)))?(\s|-)\d{3}(\s|-)\d{4}$

Explanation:

  • ^(\+0?1\s)?: Check international code
  • ((\d{3})|(\(\d{3}\)))?: Check area code
  • (\s|-): Check separator (whitespace, dash)
  • \d{3}: Check the 3 middle digits
  • (\s|-): Check separator (whitespace, dash)
  • \d{4}$: Check the last 4 digits

Example

The code:

// Define a function that checks the input string is a US/CA phone number or not
void _check(String input){
  final RegExp phone = new RegExp(r'^(\+0?1\s)?((\d{3})|(\(\d{3}\)))?(\s|-)\d{3}(\s|-)\d{4}$');
  if(phone.hasMatch(input)){
    print('$input is valid');
  } else {
    print('$input is not valid');
  }
}

// Test it
void main(){
  _check('+01 (123) 456 7890');
  _check('123 456 7890');
  _check('123 456-7890');
  _check('(123) 456-7890');
  _check('123-456-7890');
  _check('123 4432 234'); 
}

Output:

+01 (123) 456 7890 is valid
123 456 7890 is valid
123 456-7890 is valid
(123) 456-7890 is valid
123-456-7890 is valid
123 4432 234 is not valid

Final Words

Oour solution is good enough for client-side checking but it isn’t perfect. Writing a perfect regex pattern that works in any situation is super challenging even with common stuff like phone numbers, emails… It will take you a lot of time, effort, and maybe reduce the application performance.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x