Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Validate a phone number using Regex

In my Flutter mobile app, I am trying to validate a phone number using regex. Below are the conditions.

  1. Phone numbers must contain 10 digits.
  2. In case country code us used, it can be 12 digits. (example country codes: +12, 012)
  3. No space or no characters allowed between digits

In simple terms, here is are the only "valid" phone numbers

0776233475, +94776233475, 094776233475

Below is what I tried, but it do not work.

String _phoneNumberValidator(String value) {     Pattern pattern =         r'/^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/';     RegExp regex = new RegExp(pattern);     if (!regex.hasMatch(value))       return 'Enter Valid Phone Number';     else       return null;   } 

How can I solve this?

like image 468
PeakGen Avatar asked Apr 06 '19 18:04

PeakGen


People also ask

How can I check mobile number in regex?

/^([+]\d{2})? \d{10}$/ This is how this regex for mobile number is working. + sign is used for world wide matching of number.

How do I know if a cell number is valid?

Visit www.textmagic.com or download the TextMagic mobile app on google play store. Enter your phone number and country and click on Validate Number. This app will show you the status of the number if it is active or not.


1 Answers

You could make the first part optional matching either a + or 0 followed by a 9. Then match 10 digits:

^(?:[+0]9)?[0-9]{10}$ 
  • ^ Start of string
  • (?:[+0]9)? Optionally match a + or 0 followed by 9
  • [0-9]{10} Match 10 digits
  • $ End of string

Regex demo

like image 162
The fourth bird Avatar answered Sep 29 '22 06:09

The fourth bird