Creating an email address validation attribute using DataAnnotations for ASP.NET MVC

A really nice feature of the ASP.NET MVC 3 framework is it’s use of the new attributes in System.ComponentModel.DataAnnotations to provide client and server side validation on form fields.   If you’re new to DataAnnotations I suggest you go read up on them, they’re very cool!  The framework ships with a variety of default validations (mainly matching the Validator controls in WebForms) such as Required, RegularExpression and Compare. However, it lacks any specialised validators to quickly validate common data types, such as email addresses.  Luckily, DataAnnotations attributes are extensible, so we can roll our own!

namespace MyProject.Attributes.Validation
{
    using System.ComponentModel.DataAnnotations;

    public class EmailAttribute : RegularExpressionAttribute
    {
        public EmailAttribute()
            : base(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
        {
            this.ErrorMessage = "Please provide a valid email address";
        }
    }
}

In this code we define a new attribute which extends the RegularExpressionAttribute, passing our regex to its constructor (you can of course pick your email validation regular expression of choice, here is a nice summary).  We also provide a default error message.  Simple, clean, easy.  We can apply this technique to any data that can be validated with a regex: post codes, bank sort codes, urls etc.

We can now use our new attribute on our model:

using MyProject.Attributes.Validation;

public class MyModel
{
    [Required]
    [Email]
    public string EmailAddress { get; set; }
}

So now we know how to do it, don’t. Don’t roll your own. Grab the DataAnnotations Extensions and use those. It’s even easier that writing your own. The important thing is that you now know how to do this if you want to validate some other data format.

By Adam Pope

Adam is our tech God, and it's not just his name that's holy - his knowledge of code borders on the supernatural, and whilst he doesn't like to brag, he finished top of his class at university. (Yep, the very top).

When he isn't crafting masterpieces on the web he is knocking them up in the kitchen, his legendary curry being an office mainstay here at Storm.

Adam was recently named as one of South West Business Insider's 42 under 42 for 2012.

stormconsultancy.co.uk →