How to: Check if the Phone number is valid or not in Dart| Flutter By Example
This program checks how to validate the phone number validation.
Dart provides a RegExp
class for matching strings with regular expressions.
Following are the rules for valid phone numbers.
- phone number only contains numerical numbers and Optional symbol(+) only
- letters are not allowed
- Optional + or zero with beginning followed by digits from 1 to 9
- Phone number can contain 10 or 12 digits
Valid phone numbers are +9166666666666
and Invalid emails are abc
, and 123
.
Dart Mobile Phone number validation using regular expression
In this program, Phone number validation is checked using regular expressions. RegExp(regularexpression).hasMatch(phoneNumberString)
checks mobile string with a regular expression and returns a bool value.
Used regular expression is r'^(?:[+0][1-9])?[0-9]{10,12}$'
r
- indicates regular expression string ^
- String beginning (?:[+0][1-9])?
- Indicate optional + or 0 digits, followed by 1 to 9 digits [0-9]{10,12}
- match any numbers from 0 to 9 for 10 or 12 times. Here is an example program
void main() {
print(isMobileNumberValid("+9197845975511")); // true
print(isMobileNumberValid("123")); // false
print(isMobileNumberValid("879")); // false
}
bool isMobileNumberValid(String phoneNumber) {
String regexPattern = r'^(?:[+0][1-9])?[0-9]{10,12}$';
var regExp = new RegExp(regexPattern);
if (phoneNumber.length == 0) {
return false;
} else if (regExp.hasMatch(phoneNumber)) {
return true;
}
return false;
}
Output:
true
false
false
Similarly, You can add dart extensions to the String class, Extensions are adding new features to existing libraries.
Example program to write an extension for phone number validation validation
void main() {
print("+9197845975511".isMobileNumberValid()); // true
print("123".isMobileNumberValid()); // true
print("abc".isMobileNumberValid()); // true
}
extension PhoneNumberValidation on String {
bool isMobileNumberValid() {
String regexPattern = r'^(?:[+0][1-9])?[0-9]{10,12}$';
var regExp = new RegExp(regexPattern);
if (this.length == 0) {
return false;
} else if (regExp.hasMatch(this)) {
return true;
}
return false;
}
}
Conclusion
To summarize, learned how to check valid phone numbers or not in dart and flutter.