validate method
Validates the email based on user-specified options
Implementation
String? validate(String email) {
if (email.trim().isEmpty) {
return 'Email address cannot be empty !';
}
// Check minimum length
if (email.length < options.minLength) {
return 'Email address must be at least ${options.minLength} characters long !';
}
// if (options.checkFormat) {
// final emailRegex = RegExp(
// r'^(?!.*\.\.)(?!.*\.$)(?!.*\@.*\@)[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$');
// if (!emailRegex.hasMatch(email)) {
// return 'Please enter a valid email address';
// }
// }
// Separate checks for consecutive dots and trailing dots
if (options.preventConsecutiveDots && email.contains('..')) {
return 'Email address cannot contain consecutive dots !';
}
if (options.checkEndsWithDot && email.endsWith('.')) {
return 'Email address cannot end with a dot !';
}
// Prevent multiple "@" symbols
if (options.preventMultipleAtSymbols && email.split('@').length - 1 > 1) {
return 'Email address cannot contain multiple "@" symbols !';
}
// Check for common mistakes
if (options.checkCommonMistakes) {
final commonMistakes = {
'.con': '.com',
'.cim': '.com',
'.comm': '.com',
'@gnail.com': '@gmail.com',
'@gamil.com': '@gmail.com',
'@yaho.com': '@yahoo.com',
'@outlok.com': '@outlook.com',
'@hotmial.com': '@hotmail.com',
};
for (var mistake in commonMistakes.entries) {
if (email.endsWith(mistake.key)) {
return 'Did you mean "${email.replaceFirst(mistake.key, mistake.value)}" ?';
}
}
}
// Prevent disposable email domains
if (options.preventDisposableEmails) {
final disposableDomains = [
'tempmail.com',
'10minutemail.com',
'mailinator.com',
'yopmail.com',
'guerrillamail.com',
];
final emailDomain = email.split('@').last;
if (disposableDomains.contains(emailDomain)) {
return 'Disposable email addresses are not allowed !';
}
}
// Check email format
if (options.checkFormat) {
final emailRegex =
RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$');
if (!emailRegex.hasMatch(email)) {
return 'Please enter a valid email address !';
}
}
// If all checks pass
return null;
}