DEV Community

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

Posted on

6 4

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (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

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up