(First published on What the # do I know?)
We’ve seen it numerous times: Using a regular expression to validate a mail address.
Heck, you’re probably doing it yourself.
You might also recall that as a beginner, you wrote a method that use a couple of IndexOf
methods on a string to make sure it has the at sign (@
) and a dot (.
) after it.
Well, with the .Net Framework, that long, unreadable, unmaintainable regular expression can be (and should be) thrown away, never to be used again.
So, how do you validate the format of an email address without a regular expression or looping over your input string? Simple – you use the tools the framework gives you and you try to create an instance of the MailAddress
class from it.
One of the constructors of this class takes in a single string that is the address to use. This constructor will throw a FormatException
if the string is not a valid mail address format – so all you have to do in order to validate an email address is this:
public bool IsEmailAddressWellFormatted(string address)
{
try
{
var address = new MailAddress(address);
return true;
}
catch (FormatException ex)
{
return false;
}
}
And that's it!
Now you have a mail address format validation that's readable, maintainable, and can easily be transformed to an extension method to string, if you want.
Top comments (3)
Looks like there will soon be an alternative without the exception (similar to Uri.TryCreate).
Good to know!
Thanks! That's a bit of a helpful way to find out if that's a valid email. I wonder if there is a way to do it in other languages.