MVC Validation In Different Ways

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.
  1. How we can achieve Server side Validation in MVC?
  2. How can we enable client side validation in MVC?
  3. 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.
  1. Create a model and use namespace System.ComponentModel.DataAnnotations;
  2. Add attribute on our model property like
    1. [Display(Name="First Name")]  
    2.   
    3. [Required(ErrorMessage="Please provide First Name", AllowEmptyStrings = false)]  
    4.   
    5. Public string Fame {getset ;}  
    6.   
    7. [Display (Name="Last Name")] // It’s not required  
    8.   
    9. Public string Lame {getset ;}  
    10.   
    11. [Display(Name="Contact No1")]  
    12.   
    13. [Required(ErrorMessage="Please provide Contact No1", AllowEmptyStrings=false)]  
    14.   
    15. Public string ContactNo1 {getset ;}  
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:-
  1. Add reference for necessary jquery file
    1. <script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>  
  2. The second step is to call the EnableClientValidation method.
    1. @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:-
  1. We need to create a class and then we need to inherit that class to validationAttribute abstract class.
  2. We need to override below method
    1. override ValidationResult IsValid(object value, ValidationContext validationContext)
  3. 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
 
 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now