{

How to: Check if the email is valid or not in Dart| Flutter By Example


 Check if the email is valid or not in Dart and Flutter

This program checks how to validate the email address.

Dart provides a RegExp class for matching strings with regular expression

Following are the rules for a valid email address.

  • Email has different valid parts - sender name,@ symbol, and domain name
  • recipient and domain names may contain lower and upper case numbers
  • domain name contains an extension separated by a dot(.)
  • special characters are allowed in the sender’s name
  • sender name length is 64 characters
  • domain name is 256 characters

Valid emails are [email protected] and Invalid emails are abc, [email protected].

Dart email validation using regular expression

In this program, Email validation is checked using regular expressions. RegExp(regularexpression).hasMatch(emailString) checks the email string with a regular expression and returns a bool value.

Here is an example program

void main() {
  print(isEmailValid("ababc.com")); // false
  print(isEmailValid("[email protected]")); // true
  print(isEmailValid("[email protected]")); // false
}

bool isEmailValid(String email) {
  return RegExp(
          r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')
      .hasMatch(email);
}

Output:

false
true
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 string email validation

void main() {
  print("ababc.com".isEmailValid()); // false
  print("[email protected]".isEmailValid()); // true
  print("[email protected]".isEmailValid()); // false
}

extension EmailValidation on String {
  bool isEmailValid() {
    return RegExp(
            r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')
        .hasMatch(this);
  }
}

Conclusion

To summarize, learned how to check valid email or not in dart and flutter.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.