Email Validator

Often I need to validate emails so I go online and figure out the regex needed in order to validate it. Recently I came across a class from Microsoft – https://msdn.microsoft.com/en-us/library/01escwtf%28v=vs.110%29.aspx

As we all do, I figured I could do a better job and refactored it into this:

public class EmailValidator
{
    public bool IsValid(string emailAddress)
    {
        if (string.IsNullOrEmpty(emailAddress))
            return false;

        try
        {
            emailAddress = Regex.Replace(emailAddress, @"(@)(.+)$", DomainMapper,
                                  RegexOptions.None, TimeSpan.FromMilliseconds(200));

            return Regex.IsMatch(emailAddress,
                  @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                  @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                  RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
        }
        catch (RegexMatchTimeoutException)
        {
            return false;
        }
        catch (ArgumentException)
        {
            return false;
        }
    }

    private static string DomainMapper(Match match)
    {
        IdnMapping idn = new IdnMapping();
        var domainName = match.Groups[2].Value;
        domainName = idn.GetAscii(domainName);
        return match.Groups[1].Value + domainName;
    }
}