Hello Devz,

Do you have a web or WPF application that needs email address validation? Regex (regular expression) can help you. This post outlines a simple email validation regex that you can use straight away.

What is a regex?

A regular expression (regex for short) describes a search pattern using a particular text string. It’s a similar idea to wildcard notations. With a wildcard you might use *.doc to find all Word files in a file manager, while with a regex you would use ^.*\.doc$. You can also do more using regular expressions, such as searching for something very specific.

What does an email string look like?

An email string is a chain of characters followed by an ‘@’ sign followed by another chain of characters followed by a ‘.’ (dot) and another chain of characters, e.g. ‘com’, ‘org’, ‘net’, etc. These chains of characters can be upper case or lower case. They can also contain numbers and some special characters.

Is regex specific to a particular coding language?

No. In this example, I am using C#, however the regex itself can be used in many different languages.

How to do an email validation regex

It’s straightforward. All you need to do is give the email address string to be analysed by the regex. It will then return a boolean to confirm whether the email is valid or not.

Here is a simple regex you can use to validate an email address:

public static class EmailAddressHelper
{
    public static bool Validate(string emailAddress)
    {
        var regex = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
        bool isValid = Regex.IsMatch(emailAddress, regex, RegexOptions.IgnoreCase);
        return isValid;
    }
}

If you want to know more about UI validation, read my blog post about WPF – MVVM TextBox Validation with IDataErrorInfo.

Happy validation! 🙂