ASP.NET MVC 2 Model Validation
In projects I usually work on, we always use a data validation framework. But now in ASP.NET MVC 2 you can do it just as you would using a framework.
You need to write your model with the proper validation attributes.
using System;
using System.ComponentModel.DataAnnotations;
namespace FunWithMvc2RC2
{
public class Test
{
// StringLenght
[StringLength(5, ErrorMessage = "Maximum 25 Characters")]
public string StringLength { get; set; }
// Required
[Required(ErrorMessage = "Required Field")]
public string Required { get; set; }
// Required and StringLenght
[Required(ErrorMessage = "Required Field")]
[StringLength(5, ErrorMessage = "Maximum 25 Characters")]
public string Combos { get; set; }
// Range Attribute
[Range(1, 31, ErrorMessage = "Minimum 1; Maximum 31")]
public int Range { get; set; }
// RegularExpression Attribute
[RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ErrorMessage = "Invalid Email Address")]
public string Regex { get; set; }
// Custom Regular Expression EmailAttribute
[Email(ErrorMessage = "Email Validation")]
public string Email { get; set; }
}
}
This will give you something like this:

And to make the Email Attribute you simply make a new class, which inherits RegularExpressionAttribute and then send the constructor an Email Address Regex! It’s this simple. You could do the same for any other Regular Expression based validation. Just Make sure you call your class – SomethingAttribute.
using System;
using System.ComponentModel.DataAnnotations;
namespace FunWithMvc2RC2
{
public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute() :
base(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$") {}
}
}
This entry was posted on Monday, February 15th, 2010 at 12:40 pm and is filed under MVC. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


Mike February 16th, 2010 at 11:51 am
@GERARD Hey this is a good question! I haven’t worked on that yet, but I don’t have any project at the moment, so I’ll be working on that today. You should see a post about it today or tomorrow, if all goes well!