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!

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.

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.