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.