Implementing Multiple Validation Logic in MVC 4

Introduction

When developing a custom validation attribute I always prefer to use it for multiple purposes, otherwise it might be duplicated. Date validation is very important in real projects since it includes a lot of business validation logic. In this article, I will try to show you how to implement multiple validations at the server side in MVC using ASP.NET Data Annotations.

Requirement

There might be many requirements to validate a Date object. It might be required that it be in the correct format, it might be that the end date must be greater than the start date and so on. MVC provides RequiredValidator, RegularExpressionValidator, CompareValidator and so on. But if you have specific cases like the minimum date should not be less than 2014 and so on then we need to create our Custom Validation Classes. What if sometimes it requires multiple validations based on requirements? Will you create 4-5 custom validators? I am trying to address this problem.

Basics

  1. Let us first create an enum:
    1. public enum ValidationType  
    2. {  
    3.     RangeValidation,  
    4.     Compare  
    5. }  
  2. Now we will create a custom validator used for multiple validations. For that we need to inherit it from the System.ComponentModel.DataAnnotations.ValidationAttribute as in the following:
    1. [AttributeUsage(AttributeTargets.Property,AllowMultiple=true,Inherited=true)]  
    2. public class DateValidationAttribute : ValidationAttribute  
    3. {} 
    The AllowMultiple property of AttributeUsage is the key to enable multiple validations.

Solution

Let's see my implementation of the custom validator:

  1. private ValidationType _validationType;  
  2. private DateTime? _fromDate;  
  3. private DateTime _toDate;  
  4. private string _defaultErrorMessage;  
  5. private string _propertyNameToCompare;  
  6.   
  7. public DateValidationAttribute(ValidationType validationType, string message, string compareWith = ""string fromDate= "")  
  8. {  
  9.     _validationType = validationType;  
  10.     switch (validationType)  
  11.     {  
  12.         switch (validationType)  
  13.         {  
  14.             case ValidationType.Compare:  
  15.             {  
  16.                 _propertyNameToCompare = compareWith;  
  17.                 _defaultErrorMessage = message;  
  18.                 break;  
  19.             }  
  20.   
  21.             case ValidationType.RangeValidation:  
  22.             {  
  23.                 _fromDate = new DateTime(2009,1,1);  
  24.                 _toDate = DateTime.Today;  
  25.                 _defaultErrorMessage = message;  
  26.                 break;  
  27.             }  
  28.         }  
  29.     }  
  30. }  
  31.   
  32. protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
  33. {  
  34.     switch (_validationType)  
  35.     {  
  36.         case ValidationType.Compare:  
  37.         {  
  38.             var baseProperyInfo = validationContext.ObjectType.GetProperty(_propertyNameToCompare);  
  39.             var startDate = (DateTime)baseProperyInfo.GetValue(validationContext.ObjectInstance, null);  
  40.             if(value!=null)  
  41.             {  
  42.                 DateTime enteredDate = (DateTime)value;  
  43.                 if (thisDate <= startDate)  
  44.                 {  
  45.                     return new ValidationResult(_defaultErrorMessage);  
  46.                 }  
  47.             }  
  48.             break;  
  49.         }  
  50.   
  51.         case ValidationType.RangeValidation:  
  52.         {  
  53.             if(value!=null)  
  54.             {  
  55.                 DateTime enteredDate = (DateTime)value;  
  56.                 if (!(thisDate >= _fromDate && thisDate <= _toDate))  
  57.                 {  
  58.                     return new ValidationResult(_defaultErrorMessage);  
  59.                 }  
  60.             }  
  61.         }  
  62.     }  
  63.     return null;  

The IsValid method above returns the ValidationResult that is a member of System.ComponentModel.DataAnnotation. Now with these pieces of code our DateValidationAttribute class is ready to be consumed. Actually this class may require a few changes for better performance. I am still looking for some changes, like the error message can be more specific and so on. But it is well enough to proceed.

Now, let's see how to use it as our Model class's property:

  1. [Display(Name = "From Date")]  
  2. [Required]  
  3. public DateTime FromDate { getset; }  
  4. [Display(Name = "To Date")]  
  5. [Required]  
  6. [DateValidation(ValidationType.Compare, "Selected date should be Less than From Date.", compareWith: "FromDate")  
  7. public DateTime ToDate { getset; } 

Now getting to my Controller where I have created an Action method that provides a custom action on validation failure and success.

  1. public ActionResult DateValidate(AccountModel model)  
  2. {  
  3.     if (!ModelState.IsValid)  
  4.     return View(model);  
  5.     return RedirectToAction("About");  

Conclusion

Winding up all your business validation logic into one custom validator will help you to better organize your code and usage. I hope this helps.

Up Next
    Ebook Download
    View all
    Learn
    View all