Today we are going to talk about validation in MVC.
When we talk about validation in MVC, then lot of question will arise in our mind.
There are some few normal question which will asked in interview related to validation in MVC.
- How we can achieve Server side Validation in MVC?
- How can we enable client side validation in MVC?
- How can we achieve custom validation in MVC?
How we can achieve Server side Validation in MVC?
We need to perform below steps to achieve server side validation.
- Create a model and use namespace System.ComponentModel.DataAnnotations;
- Add attribute on our model property like
- [Display(Name="First Name")]
-
- [Required(ErrorMessage="Please provide First Name", AllowEmptyStrings = false)]
-
- Public string Fame {get; set ;}
-
- [Display (Name="Last Name")]
-
- Public string Lame {get; set ;}
-
- [Display(Name="Contact No1")]
-
- [Required(ErrorMessage="Please provide Contact No1", AllowEmptyStrings=false)]
-
- Public string ContactNo1 {get; set ;}
So when our model binding will happen on that time our model validation will happen and those ErrorMessage will be store in our modelstate information.
How can we enable client side validation in MVC?
For enable client side validation in MVC we need to perform below two steps:-
- Add reference for necessary jquery file
- <script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
- The second step is to call the EnableClientValidation method.
- @Html.EnableClientValidation();
How can we achieve custom validation in MVC?
But some the scenario our inbuilt validation attribute is not suitable to meet our requirement. In those situation we need to create our custom validation attribute which will meet our requirement.
In end of the day the validation attribute are nothing but class so we need to create a validation custom class.
There are basis three steps we need to follow:-
- We need to create a class and then we need to inherit that class to validationAttribute abstract class.
- We need to override below method
- override ValidationResult IsValid(object value, ValidationContext validationContext)
- In last we need to use this custom validator in our model as a validation attribute.
Let see these discussed steps as practical.
Step 1 and 2
Step 3