From Microsoft's How to: Verify that Strings Are in Valid Email Format Code Example for Microsoft's email validity check

Oh please, heavens, say it isn't so.

Sounds more like a Dune quote, doesn't it?


EDIT: Some decent advice:

Defence in depth only works if each level of your security onion is not rotten. One rotten layer means you spoil the whole onion. Rejecting "foo@example.com.au" because you want to defend against vulnerabilities in Sun's ยต-law encoding doesn't make sense, does it? Don't laugh, it's happened to me. The reason I am here commenting is that Medicare Australia doesn't allow ".au" addresses, only ".com". Also read Mark Swanson, "How not to validate email, ",ย mdswanson.com/blog/2013/10/14/โ€ฆย โ€“ย ManicDeeย Nov 22 '13 at 5:21

And then from the linked post, "How now to validate email":

Or maybe you will find a regular expression that looks something like ^[_a-z0-9-]+(\.[_a-z0-9-]omg-whyyyyy$. ... So what should you do instead? Just check for the existence of @. Every email address will have at least one of them and it is trivially easy to write this code.

As I mentioned on SO...

The buttoned up coder in me is trying to resist, but the rest is surprisingly convincingly arguing that anything else is a sad tragedy of micro-optimization.

Just fwiw, I'm also checking for a length of at least one before and after the last @, though I haven't looked at the format for comments inside of an email address [sic!!].

public static bool IsValidEmail(this string str)
{
    // See https://myfreakinname.blogspot.com/2016/10/spaghetti-code-leads-to-suffering.html#emailValidationEdit
    // for the reasoning behind this.

    int lastAtLoc = str.LastIndexOf('@');
    return lastAtLoc < str.Length - 1 && lastAtLoc > 0;
}

Labels: , , ,