How to: Check if the 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 expressions.
Below are the rules for a valid email address.
An email consists of distinct parts: the sender’s name, the ’@’ symbol, and the domain name.
Both the recipient and domain names may contain lowercase and uppercase letters.
The domain name contains an extension separated by a dot (’.’).
Special characters are allowed in the sender’s name.
The sender’s name can be up to 64 characters long.
The domain name can be up to 256 characters long.
Valid emails include
[email protected]
, while invalid ones areabc
andabc@abc
.
Dart Email Validation Using Regular Expressions
This program checks email validation using regular expressions. RegExp(regularexpression).hasMatch(emailString)
evaluates the email string with a regular expression and returns a boolean value.
Here’s an example program:
void main() {
print(isEmailValid("ababc.com")); // false
print(isEmailValid("[email protected]")); // 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 add new features to existing libraries.
Here’s an example program demonstrating how to write an extension for string email validation:
void main() {
print("ababc.com".isEmailValid()); // false
print("[email protected]".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
In summary, we’ve learned how to validate whether an email address is valid or not in Dart and Flutter.