DEV Community

Cover image for Validate mail address format the easy way
Zohar Peled
Zohar Peled

Posted on

Validate mail address format the easy way

(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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (3)

Collapse
jeikabu profile image
jeikabu

Looks like there will soon be an alternative without the exception (similar to Uri.TryCreate).

Collapse
peledzohar profile image
Zohar Peled Author

Good to know!

Collapse
michaeljota profile image
Michael De Abreu

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.