Model Validation
Model validation is the process of ensuring that the data we receive is suitable for binding to our model and, when this is not the case, providing useful information to the user that will help them correct the problem.
ASP.NET MVC supports declarative validation rules defined with attributes from the System.ComponentModel.DataAnnotations namespace. The MVC Framework provides extensive support for model validation. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength.
Create Custom Model Validation Attribute
Here we are creating CheckAgeAttribute to check that age must be between 18 to 30.
- Create an Empty project in Visual Web Developer 2010 Express of MVC3 application.


- Right click on Model directory and create class
Employee.
public class Employee
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[CheckAge] public DateTime DOB { get; set; }
[Required]
public DateTime DOJ { get; set; }
[Required]
public float Salary { get; set; }
}
- Again right click on Model directory and create class
CheckAgeAttribute. For custom validation, you have to derive this class from ValidationAttribute.
public class CheckAgeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid
(object value, ValidationContext validationContext)
{
return ValidationResult.Success;
}
}
- To implement the validation logic, you need to override one of the
IsValid methods provided by the base class. Overriding the IsValid version taking a ValidationContext parameter provides more information to use inside the IsValid method (the ValidationContext parameter will give you access to the model type, model object instance, and friendly display name of the property you are validating, among other pieces of information).
public class CheckAgeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid
(object value, ValidationContext validationContext)
{
DateTime dtV = (DateTime)value;
long lTicks = DateTime.Now.Ticks - dtV.Ticks;
DateTime dtAge = new DateTime(lTicks);
string sErrorMessage = "Age>=18 and Age<=30.
Your Age is " + dtAge.Year.ToString() + " Yrs.";
if (!(dtAge.Year >= 18 && dtAge.Year <= 30))
{ return new ValidationResult(sErrorMessage); }
return ValidationResult.Success;
}
}
The first parameter to the IsValid method is the value to validate. If the value is valid, you can return a successful validation result, but before you can determine if the value is valid, you’ll need to check value according to your validation condition, in our case condition is Age>=18 and Age<=30. And you return a ValidationResult object with a hard-coded error message to indicate a validation error.
- Right click on controller, create
Home and write in Create() method of HomeController.
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Employee newEmployee)
{
if (ModelState.IsValid)
{
}
return View();
}
- Right click on
Create() method of HomeController and add strongly typed view, select scaffold template, create then ok.

- Open Global.asax.cs and change action value
Index to Create in RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", "{controller}/{action}/{id}", id = UrlParameter.Optional } new { controller = "Home", action = "Create",
id = UrlParameter.Optional } );
}
- Build and run the application.
History
- 26th September, 2011: Initial version