Understanding Validation in MVC - Part 3

This article is continuation of previous article,

This article focuses on implementing custom validation in MVC.

Custom Validation:

Custom Validation allows you to create your own validation attribute. For this you need to implement data annotation concept. You need to extend the class ValidationAttribute.

Let’s see this class

custom validation

ValidationAttribute is abstract class, has various method which will helps you to write your own method for validation.

We have following steps to implement it.

Step 1:
Define Custom attribute class, remember base class must be ValidationAttribute. And override the suitable method for your implementation. Below is my implementation.

  1. public class DuplicateNameCheck: ValidationAttribute   
  2. {  
  3.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
  4.     {  
  5.         DateTime dateTime = Convert.ToDateTime(value);  
  6.         if (value != null)  
  7.         {  
  8.             if (dateTime < DateTime.Today)   
  9.             {  
  10.                 return ValidationResult.Success;  
  11.             }   
  12.             else  
  13.             {  
  14.                 return new ValidationResult("Invalid Date. " + validationContext.DisplayName + " should be past date");  
  15.             }  
  16.         }  
  17.       else             
  18.      return new ValidationResult("" + validationContext.DisplayName + " is required");  
  19.     }  
  20. }  
Step 2: Apply the custom attribute to the property. You may customize the message:

attribute

Step 3: Finally validate the controller:

controller

Case 4: Write the postback action:
  1. [HttpPost]  
  2. public ActionResult Index(StudentDetailsModel model)   
  3. {  
  4.     if (ModelState.IsValid)   
  5.     {  
  6.         // your validation successful code ( like save data)  
  7.     }  
  8.     return View(model);  
  9. }  
Step 5: Execute the project you will find validation message on post back:
validation message

Remember this validation is performed on postback.

I hope you understood how remote validations is performed in MVC. In my next article we will see Validation Summary. 


Similar Articles