/// <summary>
/// Validates the email if it follows the valid email format
/// </summary>
/// <param name="emailAddress"></param>
/// <returns></returns>
public static bool EmailIsValid(string emailAddress)
{
//if string is not null and empty then check for email follow the format
return string.IsNullOrEmpty(emailAddress)?false : new Regex(@"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$", RegexOptions.IgnoreCase).IsMatch(emailAddress);
}
For the simple email like goerge@xxx.com, below code is sufficient.
public static bool ValidateEmail(string email)
{
System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
System.Text.RegularExpressions.Match emailMatch = emailRegex.Match(email);
return emailMatch.Success;
}
public cass User
{
public string Email { get; set; }
}
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(x => x.Email).EmailAddress().WithMessage("The text entered is not a valid email address.");
}
}
// Validates an user.
var validationResult = new UserValidator().Validate(new User { Email = "açflkdj" });
// This will return false, since the user email is not valid.
bool userIsValid = validationResult.IsValid;
public static bool IsValidEmail(this string email)
{
// skip the exception & return early if possible
if (email.IndexOf("@") <= 0) return false;
try
{
var address = new MailAddress(email);
return address.Address == email;
}
catch
{
return false;
}
}
public static bool IsEmail(this string input)
{
if (string.IsNullOrWhiteSpace(input)) return false;
// MUST CONTAIN ONE AND ONLY ONE @
var atCount = input.Count(c => c == '@');
if (atCount != 1) return false;
// MUST CONTAIN PERIOD
if (!input.Contains(".")) return false;
// @ MUST OCCUR BEFORE LAST PERIOD
var indexOfAt = input.IndexOf("@", StringComparison.Ordinal);
var lastIndexOfPeriod = input.LastIndexOf(".", StringComparison.Ordinal);
var atBeforeLastPeriod = lastIndexOfPeriod > indexOfAt;
if (!atBeforeLastPeriod) return false;
// CODE FROM COGWHEEL'S ANSWER: https://stackoverflow.com/a/1374644/388267
try
{
var addr = new System.Net.Mail.MailAddress(input);
return addr.Address == input;
}
catch
{
return false;
}
}
public static bool ValidateEmail(string value, bool required, int minLength, int maxLength)
{
value = value.Trim();
if (required == false && value == "") return true;
if (required && value == "") return false;
if (value.Length < minLength || value.Length > maxLength) return false;
//Email must have at least one character before an @, and at least one character before the .
int index = value.IndexOf('@');
if (index < 1 || value.LastIndexOf('.') < index + 2) return false;
return true;
}