{

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


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 abc@ch.com and Invalid emails are abc, abc@abc.

Dart email validation using regular expression

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

Here is an example program

void main() {
  print(isEmailValid("ababc.com")); // false
  print(isEmailValid("abc@abc.com")); // true
  print(isEmailValid("abc@abc")); // 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("abc@abc.com".isEmailValid()); // true
  print("abc@abc".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.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example