In my last post, I talked about how ASP.NET MVC 2.0 Preview 1 has built-in support for validating classes using System.ComponentModel.DataAnnotations:
Absolutely love that as now we don't have to create Custom ModelBinders just to sneak in a more robust validation framework in replace of IDataErrorInfo support in ASP.NET MVC 1.0!
In the previous post, I showed a Contact Class filled with several ValidationAttribute (s) and other metadata that looks a little crazy to maintain and certainly can be distracting to the eye:
public class Contact
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required.")]
[StringLength(200, ErrorMessage = "Email must be 200 characters or less.")]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
public string Email { get; set; }
}
We can clean this up a bit by moving these attributes to a buddy class, which you probably remember from ASP.NET DynamicData. Buddy Classes are not specific to DynamicData, but since that is where they got their first start, we just end up thinking that way ( or at least I do ).
( Aside: See ASP.NET Dynamic Data Tutorial - BuddyMetadataProvider and Custom Metadata Providers )
I can go ahead and create a separate buddy class that holds those ValidationAttribute (s) on behalf of the Contact Entity as such:
internal class Contact_Metadata
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required.")]
[StringLength(200, ErrorMessage = "Email must be 200 characters or less.")]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]
[DataType(DataType.EmailAddress)]
[DisplayName("Email Address")]
public string Email { get; set; }
}
and then remove those ValidationAttributes as well as decorate the Contact Entity with a special attribute pointing to the buddy class:
[MetadataType(typeof(Contact_Metadata))]
public class Contact : Entity
{
public string Name { get; set; }
public string Email { get; set; }
}
and the code in the previous post ( DefaultModelBinder Supports DataAnnotations and ValidationAttribute (s) in ASP.NET MVC 2.0 ) works the same!
I will be presenting all these new ASP.NET MVC 2.0 Features as well as others at the next Tampa ASP.NET MVC Developer Group Meeting!
David Hayden
ASP.NET MVC Tutorials