Best Regular Expression for Email Validation in C#
Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Usage :
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
First option (bad because of throw-catch, but MS will do work for you):
bool IsValidEmail(string email)
{
try {
var mail = new System.Net.Mail.MailAddress(email);
return true;
}
catch {
return false;
}
}
Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification
This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.
public static bool isValidEmail(string inputEmail)
{
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
Updated answer for 2019.
Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
public static bool IsValidEmailFormat(string emailInput)
{
return _regex.IsMatch(emailInput);
}
Alternative Configuration for Regex:
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.
Thread Safety And Regex
Regex Best Practices
I would like to suggest new EmailAddressAttribute().IsValid(emailTxt)
for additional validation before/after validating using RegEx
Remember EmailAddressAttribute
is part of System.ComponentModel.DataAnnotations namespace
.