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 false;
}
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
}
Creator of Coflutter.
Founder & CTO at Bumbii Technology
Founder at Bumbii K12
Follow him on Twitter, Github, StackOverflow, LinkedIn, Upwork.
Thank you very much! This helped me in my assignment!