ASP.NET MVC 2 Model Validation
February 15th, 2010 / 5 Comments » / by Mike
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}$") {}
}
}




