ASP.Net MVC Client Side Validation

This article explains how to implement client-side validation in an ASP.NET MVC application. The validation implemented using jQuery and jQuery validation plug-in (jquery.validate.min.js and jquery.validate.unobtrusive.min.js).

In the server-side validation, the page must be submitted via a postback to be validated on the server and if the model data is not valid then the server sends a response back to the client with client-side validation, the input data is checked as soon as they are submitted, so there is no postback to the server and there is no page refresh.

When you are developing an MVC application in Visual Studio 2012 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.

  1. <configuration>  
  2.   <appSettings>     
  3.     <add key="ClientValidationEnabled" value="true" />  
  4.     <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
  5.   </appSettings>  
  6. </configuration>  
The jQuery validation plug-in takes advantage of the Data Annotation attributes defined in the model, which means that you need to do very little to start using it. Let's create an Employee model (Employee.cs class file under the Models folder) that has two properties with Data annotation attributes.

 

  1. using System.ComponentModel.DataAnnotations;  
  2. namespace ClientValidation.Models  
  3. {  
  4.     public class Employee  
  5.     {  
  6.         [Required(ErrorMessage = "Name is Requirde")]  
  7.         public string Name { getset; }  
  8.         [Required(ErrorMessage = "Email is Requirde")]  
  9.         [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  10.                             @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  11.                             @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",  
  12.                             ErrorMessage = "Email is not valid")]  
  13.         public string Email { getset; }  
  14.     }  
  15. }  
After that you need to create the controller's action methods. These render views on the UI and bind a model with the view. So let's create a controller with two action methods that handle both request types (GET and POST respectively).
  1. using System.Web.Mvc;  
  2. using ClientValidation.Models;   
  3. namespace ClientValidation.Controllers  
  4. {  
  5.     public class EmployeeController : Controller  
  6.     {  
  7.         public ActionResult Index()  
  8.         {  
  9.             return View();  
  10.         }   
  11.         [AcceptVerbs(HttpVerbs.Post)]  
  12.         public ActionResult Index(Employee model)  
  13.         {  
  14.             if (ModelState.IsValid)  
  15.             {  
  16.                 ViewBag.Name = model.Name;  
  17.                 ViewBag.Email = model.Email;  
  18.             }  
  19.             return View(model);  
  20.         }  
  21.     }  
  22. }
Now create a view by right-clicking on the action method then click on "Add View" as:

image1.gif

Figure 1.1 : Add New View Screen

Here I checked "Reference script libraries"which means Visual Studio adds these references automatically. Visual Studio adds the following code snippet to the bottom of the view.
  1. @section Scripts {  
  2.     @Scripts.Render("~/bundles/jqueryval")  
  3. }  
  4.   
  5. Now click on the "Add" button and the view is created as in the following code snippet:  
  6.   
  7. @model ClientValidation.Models.Employee  
  8. @{  
  9.     ViewBag.Title = "Index";  
  10. }  
  11.  @if (ViewData.ModelState.IsValid)  
  12.     {  
  13.         if(@ViewBag.Name != null)  
  14.         {  
  15.             <b>  
  16.                 Name : @ViewBag.Name<br />  
  17.                 Email : @ViewBag.Email  
  18.             </b>  
  19.         }  
  20.     }   
  21. @using (Html.BeginForm()) {  
  22.     @Html.ValidationSummary(true)   
  23.     <fieldset>  
  24.         <legend>Employee</legend>   
  25.         <div class="editor-label">  
  26.             @Html.LabelFor(model => model.Name)  
  27.         </div>  
  28.         <div class="editor-field">  
  29.             @Html.EditorFor(model => model.Name)  
  30.             @Html.ValidationMessageFor(model => model.Name)  
  31.         </div>   
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(model => model.Email)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.             @Html.EditorFor(model => model.Email)  
  37.             @Html.ValidationMessageFor(model => model.Email)  
  38.         </div>   
  39.         <p>  
  40.             <input type="submit" value="Create" />  
  41.         </p>  
  42.     </fieldset>  
  43. }  
  44. @section Scripts {  
  45.     @Scripts.Render("~/bundles/jqueryval")  
  46. }  
Let's run the application and test the following scenario.
  1. When all fields are empty:

    image2.gif
    Figure 1.2: Validation Message when both fields are empty
     
  2. When the Name field is empty but Email is not valid:

    image3.gif
    Figure 1.3 : Validation Message when Email is not valid
     
  3. When both fields are valid:

    image4.gif
    Figure 1.4 All fields are valid


Similar Articles