-2.9 C
New York
Wednesday, February 1, 2023

Dart regex to validate US/CA phone numbers

Image source: Pixabay

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:Advertisements

(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?1s)?((d{3})|((d{3})))?(s|-)d{3}(s|-)d{4}$

Explanation:

  • ^(+0?1s)?: 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 is reusable
void _check(String input) {
  final RegExp phone =
      RegExp(r'^(+0?1s)?((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');
}

AdvertisementsOutput:

+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

Our 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.

Continue learning more new and fascinating things about modern Flutter by taking a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles