Click here to Skip to main content
11,716,249 members (85,264 online)
Click here to Skip to main content

Custom Validation Attribute in ASP.NET MVC3

, 26 Sep 2011 CPOL 57.2K 1.2K 19
Rate this:
Please Sign up or sign in to vote.
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.
Output Image

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.

  1. Create an Empty project in Visual Web Developer 2010 Express of MVC3 application.

    Output Image

    Output Image

  2. 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] //custom attribute
        public DateTime DOB { get; set; }
    	[Required]
        public DateTime DOJ { get; set; }
    	[Required]
        public float Salary { get; set; }
     }
  3. 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;
      }
    }
  4. 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.

  5. 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)
        {
            //insert code here
        }
        return View();
    }
  6. Right click on Create() method of HomeController and add strongly typed view, select scaffold template, create then ok.

    Output Image

  7. 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", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            //new { controller = "Home", action = "Index", 
    		id = UrlParameter.Optional } // Parameter defaults
    		new { controller = "Home", action = "Create", 
    		id = UrlParameter.Optional } // Parameter defaults
        );
    }
  8. Build and run the application.

History

  • 26th September, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

R S Dodiya
Software Developer (Senior)
India India

You may also be interested in...

Comments and Discussions

 
QuestionThanks for great article, have a question Pin
@dh@r12-Sep-14 10:18
member@dh@r12-Sep-14 10:18 
Questioninteresting: how to set get min / max date range values Pin
Member 924745417-Jan-13 9:05
memberMember 924745417-Jan-13 9:05 
GeneralMy vote of 5 Pin
James D Shaw20-Jun-12 6:24
memberJames D Shaw20-Jun-12 6:24 
Question[My vote of 1] a few notes Pin
Seishin#26-Sep-11 4:15
memberSeishin#26-Sep-11 4:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150901.1 | Last Updated 26 Sep 2011
Article Copyright 2011 by R S Dodiya
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid