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

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 3: Finally validate the controller:

Case 4: Write the postback action:
- [HttpPost]
- public ActionResult Index(StudentDetailsModel model)
- {
- if (ModelState.IsValid)
- {
- // your validation successful code ( like save data)
- }
- return View(model);
- }

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.

Jaipal ReddyPosted Dec 4, 2015, 11:16 PM
Nice share.
Ankur MistryPosted Dec 1, 2015, 1:32 AM
good one Ajay
Humayun Kabir MamunPosted Nov 17, 2015, 11:12 PM
Nice...
Ajay GandhiPosted Nov 16, 2015, 8:14 AM
Thanks Everyone
Rupali ShindePosted Nov 14, 2015, 4:06 AM
nice
Jasminder SinghPosted Nov 14, 2015, 2:45 AM
That's very short and nice explanation series...!!!
Gowtham RajamanickamPosted Nov 14, 2015, 12:49 AM
good
Harshad PansuriyaPosted Nov 13, 2015, 10:58 PM
Nice one
Santhakumar MunuswamyPosted Nov 13, 2015, 10:00 AM
Good one
Anu VPosted Nov 13, 2015, 3:57 AM
this one is very helpful for me..
Sibeesh VenuPosted Nov 13, 2015, 3:52 AM
Nice
Banketeshvar NarayanPosted Nov 13, 2015, 3:37 AM
nice sharing