How to validate Phone number in Dart/Flutter

Like any other programming language, Dart supports RegExp (Regular Expression). In this post I will show you how to validate Phone number using RegExp in Dart.

First, we write a method to validate the phone number:

///
/// Check if a phone number if valid or not.
/// [phoneNumber] The phone number which will be validated.
/// Return true if the phone number is valid. Otherwise, return false.
bool isValidPhoneNumber(String phoneNumber) {
  // You may need to change this pattern to fit your requirement.
  // I just copied the pattern from here: https://regexr.com/3c53v
  final pattern = r'^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$';
  final regExp = RegExp(pattern);

  if (phoneNumber == null || phoneNumber.isEmpty) {
    return false;
  }

  if (!regExp.hasMatch(phoneNumber)) {
    return false;
  }
  return true;
}

Then we do some tests:

main() {
  final emptyPhoneNumber = '';
  final phoneNumber1 = '000';
  final phoneNumber2 = '0971234567';
  final phoneNumber3 = '+84 0971234567';
  final phoneNumber4 = '+84 971234567';
  final phoneNumber5 = '+840971234567';
  final phoneNumber6 = '+84971234567';
  final phoneNumber7 = '084971234567';
  final phoneNumber8 = '84971234567';

  print('Empty string -> ${isValidPhoneNumber(emptyPhoneNumber)}');
  print('$phoneNumber1 -> ${isValidPhoneNumber(phoneNumber1)}');
  print('$phoneNumber2 -> ${isValidPhoneNumber(phoneNumber2)}');
  print('$phoneNumber3 -> ${isValidPhoneNumber(phoneNumber3)}');
  print('$phoneNumber4 -> ${isValidPhoneNumber(phoneNumber4)}');
  print('$phoneNumber5 -> ${isValidPhoneNumber(phoneNumber5)}');
  print('$phoneNumber6 -> ${isValidPhoneNumber(phoneNumber6)}');
  print('$phoneNumber7 -> ${isValidPhoneNumber(phoneNumber7)}');
  print('$phoneNumber8 -> ${isValidPhoneNumber(phoneNumber8)}');
}

And here is the output:

Empty string -> false
000 -> true // I am not really sure if there is any phone number like this, but it looks incorrect!!!
0971234567 -> true
+84 0971234567 -> true
+84 971234567 -> true
+840971234567 -> true
+84971234567 -> true
084971234567 -> true
84971234567 -> true
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x