0

Currently I'm using this code:

    public static bool IsEmailAddress(this string value)
    {
        try
        {
            new System.Net.Mail.MailAddress(value);
            return true;
        }
        catch ()
        {
            return false;
        }
    }

Is there a way to do this without using exceptions?

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
  • There is no public built-in API for that; sorry. – SLaks Nov 16 '17 at 17:48
  • Use a regular expression, that would be the easiest way. – Igor Nov 16 '17 at 17:49
  • Sigh. I opened a bug report. Please up-vote: https://github.com/dotnet/corefx/issues/25295 – Jonathan Allen Nov 16 '17 at 17:51
  • Meh, you can write your own `TryParse` extension, would be super simple. – DavidG Nov 16 '17 at 17:52
  • @Igor That's silly. To do it with RegEx would take even more code than this and it would be less accurate. – Jonathan Allen Nov 16 '17 at 17:52
  • @DavidG That's what I'm dong now. But there are performance and debugging implications with unnecessarily throwing and catching exceptions. (Though later versions of VS make the debugging somewhat less painful.) – Jonathan Allen Nov 16 '17 at 17:53
  • 1
    Validation by exception is nasty though, RegEx is pretty simple and really not a lot of code. – DavidG Nov 16 '17 at 17:54
  • 1
    In general catching all exceptions should be avoided, and it’s best practice to only catch exceptions you expect. In this case here you should restrict it to FormatException and maybe ArgumentException if you want to handle empty and null mail addresses. – ckuri Nov 16 '17 at 18:54

1 Answers1

1

You could use a regular expression.

private const string EmailRegularExpression = @"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
private static Regex EmailValidRegex = new Regex(CommonValues.EmailRegularExpression, RegexOptions.Compiled | RegexOptions.IgnoreCase)

public static bool IsEmailValid(string emailAddress)
{
    return !string.IsNullOrWhiteSpace(emailAddress) && EmailValidRegex.IsMatch(emailAddress);
}

See also http://www.regular-expressions.info/email.html which is where I snagged the expression from.

Igor
  • 60,821
  • 10
  • 100
  • 175