Model Validtion or Validation in MVC


Introduction

There are various articles are available for model validation in MVC project, this article describes little details how to handle error In MVC which is effective and every developer must know.

Getting Started

MVC provides Data Annotations for model validation , this data annotations works in both client side code (in view that HTML page) and server side code (in controller), often this is very easiest way of error handling in today’s day.

Data annotations are attributes like Required, Range and StringLength etc. which needs to implement on the property of a class to implement validation like below example.

 public class TestModel  
   {  
     [Required(ErrorMessage = "ID is required")]  
     public int ID { get; set; }  
     [Required(ErrorMessage = "Description is required")]  
     public string Description { get; set; }  
   }  

Most used Data Annotation attributes

  1. Required: Checks value of property, if empty or null gives error message.
  2. Range : Checks ranges of property value, if value not fit in the specified range then give error message.
  3. MinLength : Check minimum length of value.
  4. MaxLength: Check maximum length of value.
  5. StringLengt: Length of value should be specified length, otherwise raises error.
Errors message can be checked and displayed in view using both c#(controller) and HTML(view) code. For displaying error message using client-side code, there are two HTML methods available in MVC that is Html.ValidationSummary() and Html.ValidationMessageFor.

The validation summery method is used to display all the error messages in one go and takes Boolean value to decide where error message should display or not(true to display messages).

Html.ValidationMessageFor method displays error messages against bound property.
Code Example:
 <%: Html.ValidationSummary(true) %>  
 <%: Html.ValidationMessageFor(model => model.ID) %>  
 <%: Html.ValidationMessageFor(model => model.Description) %>  

As I mentioned above error message can be checked and displayed in view using server side code, below example describes how to check and display error message.
 ModelState["ID"].Errors.Add("KAILASH");  
 ModelState.AddModelError("ID", "ID should be greater than 0");  
 ModelState.AddModelError("Description", "Description should be value");  
MVC supports error validation in both client side and server side, below code example describes how to validate model in server side.
 if (!ModelState.IsValid)  
 {  
  return View(testModel);  
 }  
 if (model.ID == 0)  
  ModelState.AddModelError("ID", "ID should be greater than 0");  
Above code first checks whether model is valid or not, if no error exists in model the IsValid reture true, second code adds error into model using ModelState. For custom model object to validate model explicitly MVC provides TryUpdateModel , which you can call in your controller to check if the object is valid or not.
 // TODO: Add insert logic here  
         if (TryUpdateModel(testModel) == false)  
         {  
           return View(testModel);  
         }  
         else  
         {  
           // perform action with model  
           if (testModel.ID == 0)  
             ModelState.AddModelError("ID", "ID should be greater than 0");  
           return View(testModel);  
         }  
To enable validation in client side(View), need to follow two steps, first reference the necessary jQuery files. The second step is to call the EnableClientValidation method. When you are developing an MVC application in Visual Studio 2012 or later version then the client-side becomes enabled by default, but you can easily enable or disable the writing of the following app setting code snippet in the web.config file.




 <configuration>  
  <appSettings>    
   <add key="ClientValidationEnabled" value="true" />  
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
  </appSettings>  
 </configuration>  
Step-1 :Refering jQuery files
 <script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>  
 <script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>  
 <script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>   
Step-2
 <% Html.EnableClientValidation(); %>   

Summary

Hope this article may help you to implement error handlingin MVC, enjoy and happy coding.

Thanks