(First published on What the # do I know?)
A while ago I’ve blogged about an easy way to validate mail address, without using long, unreadable, unmaintainable regular expressions.
As it turns out, my suggestion is somewhat lacking, because the format validation in the MailAddress constructor is less than perfect, allowing some invalid string formats to generate a valid mail address.
Here's what David Shulman from Microsoft had written on the subject:
We've gotten a lot of questions on this topic over the years. The short answer is that the MailAddress constructor is never going to be up-to-date versus manually using a regex. Changing the parser inside the constructor to fix bugs will break some applications. So, we have refrained from changing the behavior of this class.
Do we need to remove mention of it from this regex topic, where it's presented as the preferred alternative to a regex?
Yes, I would remove that language. Using a regex using the most recent RFC definitions would be the best choice.
Microsoft have published a document called How to verify that strings are in valid email format but there has been an on going debate on this article - mainly about problems spotted in the regular expression featured there - you can start with the comments section at the bottom of the page to see what I mean. Personally, I found following all the suggestions and links from there a little discouraging - seems like there's no consensus on what exactly that email validation regular expression should contain.
Therefore, I think that even with Microsoft’s discouragement, I would still recommend not to use a regular expression to validate an email address format.
In the end, the only real way to validate an email address is to send a confirmation email to that address and get a response – just like any major website registration process does.
Validating the mail address format should be a first step, but it absolutely can not the only step in validation the address itself – if the format isn’t valid you shouldn’t try to send the confirmation email – but that’s about all it’s good for – giving your user a heads up and stop the registration process as early as possible.
IMHO, A few false positives is not a good enough reason to use a far more cumbersome code.
Level up every day