In my Flutter mobile app, I am trying to validate a phone number using regex
. Below are the conditions.
- Phone numbers must contain 10 digits.
- In case country code us used, it can be 12 digits. (example country codes: +12, 012)
- 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?
Best Answer
You could make the first part optional matching either a
+
or 0 followed by a 9. Then match 10 digits:^
Start of string(?:[+0]9)?
Optionally match a+
or0
followed by 9[0-9]{10}
Match 10 digits$
End of stringRegex demo