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, 6:16 PM EST
Nice share.
Ankur MistryTOP 100Posted Nov 30, 2015, 8:32 PM EST
good one Ajay
Humayun Kabir MamunPosted Nov 17, 2015, 6:12 PM EST
Nice...
Ajay GandhiPosted Nov 16, 2015, 3:14 AM EST
Thanks Everyone
Rupali ShindePosted Nov 13, 2015, 11:06 PM EST
nice
Jasminder SinghPosted Nov 13, 2015, 9:45 PM EST
That's very short and nice explanation series...!!!
Gowtham RajamanickamTOP 100Posted Nov 13, 2015, 7:49 PM EST
good
Harshad PansuriyaPosted Nov 13, 2015, 5:58 PM EST
Nice one
Santhakumar MunuswamyPosted Nov 13, 2015, 5:00 AM EST
Good one
Anu VPosted Nov 12, 2015, 10:57 PM EST
this one is very helpful for me..
Sibeesh VenuTOP 100Posted Nov 12, 2015, 10:52 PM EST
Nice
Banketeshvar NarayanPosted Nov 12, 2015, 10:37 PM EST
nice sharing