{

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

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example