Custom Validation With IValidatableObject in MVC

In this article, you will learn how to create a self validating object using IValidatableObject to validate data in MVC.
 
Let's look at a situation where we will implement an IValidatableObject to enable date validation.
 
 
 
In the above form, you can see that the Date of Birth is in the future which is wrong from every perspective. So to validate this date we can implement IValidatableObject, let's see how.
 
Now, follow the instructions from here.
 
Step 1
 
Open model and implement the IValidatableObject interface. You can get this pop-up by pressing Ctrl+. (dot). It implements a validatable interface automatically in Visual Studio.
 
 
 
When you click on "Implement interface 'IValidatableObject'" you will have the following interface. This will return IEnumerable<ValidationResult> by taking one parameter as ValidationContext.
 
 
 
Step 2
 
Now, in the above context we can implement our validation checks as given below.
 
 
 
In the above self-validation context I have implemented two checks. First, is date in future? Second, is date in too past? If condition matches will return the validation result.
 
Step 3
 
Run the application and test it. It will work fine with two unavoidable bugs.
 
First, the newly added validation will only work when you click the button, however it should immediately report the error if the selected date is in the future or too far in the past.
 
Second, the validation error message should be displayed with the Date of Birth TextBox.
 
 
 
Step 4
 
Actually, by default every error message is placed here (in the following image) and that is why we are getting the error message on the top.
 
 
 
Also, the reason of this error is that we didn't associat the returned validation result with an appropriate property in the model.
 
Step 5
 
To associate the model property with a validation result, let's make the following changes.
 
 
 
Created a variable that will contain a list of model properties because ValidationResult only accepts IEnumerable data (look at the intellisense in the above image) and the reason is a ValidationResult can be applied to multiple model properties.
 
Now, if you run the application at this point you will see everything working. Awesome.
 
 
 
Hope this helps.


Similar Articles