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.
- public class DuplicateNameCheck: ValidationAttribute
- {
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- DateTime dateTime = Convert.ToDateTime(value);
- if (value != null)
- {
- if (dateTime < DateTime.Today)
- {
- return ValidationResult.Success;
- }
- else
- {
- return new ValidationResult("Invalid Date. " + validationContext.DisplayName + " should be past date");
- }
- }
- else
- return new ValidationResult("" + validationContext.DisplayName + " is required");
- }
- }
Step 2: Apply the custom attribute to the property. You may customize the message:
Step 3: Finally validate the controller:
Case 4: Write the postback action:
- [HttpPost]
- public ActionResult Index(StudentDetailsModel model)
- {
- if (ModelState.IsValid)
- {
-
- }
- return View(model);
- }
Step 5: Execute the project you will find validation message on post back:
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.