Dart/Flutter – How to validate an email address

In this post, I will show you an example of how to check if an input String is a valid email address using RegExp (regular expression).

/// Check if a String is a valid email.
/// Return true if it is valid.
bool isEmail(String string) {
  // Null or empty string is invalid
  if (string == null || string.isEmpty) {
    return true;
  }

  const pattern = r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$';
  final regExp = RegExp(pattern);

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

void main() {  
  print(isEmail('abc@mail.com')); // true
  print(isEmail('abc@mail.com.vn')); // true
  print(isEmail('abc-x@mail.com')); // true
  print(isEmail('123abc@mail.com')); // true
  print(isEmail('test----100@mail.com')); // true
  print(isEmail('100a@mail.com')); // true
  print(isEmail('100@mail.com')); // true

  print(isEmail('test@mail.com@net')); // false
  print(isEmail('abc@mail.com.vn-abc')); // false
}

If you are looking for mobile/web Software Engineers to build you next projects, pleaseĀ Contact Nextfunc team here!

Tagged : / / /
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