Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

    Introduction:

          Unobtrusive client side validation is one of the great feature that I like in ASP.NET MVC 3. Unobtrusive client side validation feature uses the famous jQuery validation plug-in internally. Jquery validation plug-in perform client side validation lazily. What does this means? This simply means that before submitting the form for the first time, the user can tab through fields without getting any error message. This makes sense and lot of developers and designers like this behavior. But guys coming from places where validation is performed when fields focus out, may not like this behavior. In this article, I will show you how to perform validation on fields when fields focus out.

 

    Description:

          Firstly, let's see the default behavior in action. Create a new ASP.NET MVC 3 application. Then just open(or create) HomeController.cs file and add the following code,

 

         public ActionResult Index()
         {
            return View();
         } 

 

          Next create a new class file UserInformation.cs inside Model folder and add the following code,

 

          public class UserInformation
          {
              public int Id { get; set; }

              [Required(ErrorMessage = "First Name is required")]
              [StringLength(10, ErrorMessage = "First Name max length is 10")]
              public string FirstName { get; set; }

              [Required(ErrorMessage = "Last Name is required")]
              [StringLength(10, ErrorMessage = "Last Name max length is 10")]
              public string LastName { get; set; }

              [Required(ErrorMessage = "Email is required")]
              [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")]
              public string Email { get; set; }
          }

 

          Next open(or create) Index view and add the following lines,

 

          <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<EagerlyPerformingValidation.Models.UserInformation>" %>

          <!DOCTYPE html>

          <html>
          <head runat="server">
              <title>Index</title>
	    <link href="<%: Url.Content("~/Content/Site.css") %>" rel="stylesheet" type="text/css" />
          </head>
          <body>
              <script src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js") %>" type="text/javascript"></script>
              <script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
              <script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
    
              <% using (Html.BeginForm()) { %>
                  <%: Html.ValidationSummary(true) %>
                  <fieldset>
                      <legend>UserInformation</legend>
    
                      <%: Html.HiddenFor(model => model.Id) %>
    
                      <div class="editor-label">
                          <%: Html.LabelFor(model => model.FirstName) %>
                      </div>
                      <div class="editor-field">
                          <%: Html.EditorFor(model => model.FirstName) %>
                          <%: Html.ValidationMessageFor(model => model.FirstName) %>
                      </div>
    
                      <div class="editor-label">
                          <%: Html.LabelFor(model => model.LastName) %>
                      </div>
                      <div class="editor-field">
                          <%: Html.EditorFor(model => model.LastName) %>
                          <%: Html.ValidationMessageFor(model => model.LastName) %>
                      </div>
    
                      <div class="editor-label">
                          <%: Html.LabelFor(model => model.Email) %>
                      </div>
                      <div class="editor-field">
                          <%: Html.EditorFor(model => model.Email) %>
                          <%: Html.ValidationMessageFor(model => model.Email) %>
                      </div>
    
                      <p>
                          <input type="submit" value="Save" />
                      </p>
                  </fieldset>
              <% } %>
    
              <div>
                  <%: Html.ActionLink("Back to List", "Index") %>
              </div>
          </body>
          </html>

 

         Now just run this application. You will see jQuery validation plug-in perform client side validation lazily, i.e, users can tab through fields without getting any error message before submitting the form for the first time. Now for performing validation eagerly, i.e, performing validation each time when users fields focus out, you need to add this script at bottom of the page.

 

          <script type="text/javascript">
                    $(document).ready(function () {
                              $('input','form').blur(function () {
                                        $(this).valid();
                              });
                    });
          </script>

 

         Update: There is another way which I feel better and simple,

 

          <script type="text/javascript">
                    $(document).ready(function () {
                              var settngs = $.data($('form')[0], 'validator').settings;
                              settngs.onfocusout = function (element) { $(element).valid(); };
                    });
          </script>

 

 

         Now, just run your application again. You will see the validation behavior become eager. Now, let's say that you need to add this behavior to all of your views. Adding this script to all of your views may be pain for you. For making this behavior possible in all of your views without adding this script to every view, you need to open jquery.validate.unobtrusive(.min).js file and then replace this script,

 

          options: {  // options structure passed to jQuery Validate's validate() method
                    errorClass: "input-validation-error",
                    errorElement: "span",
                    errorPlacement: $.proxy(onError, form),
                    invalidHandler: $.proxy(onErrors, form),
                    messages: {},
                    rules: {},
                    success: $.proxy(onSuccess, form)
          },

 

         with this script, 

 

          options: {  // options structure passed to jQuery Validate's validate() method
                    errorClass: "input-validation-error",
                    errorElement: "span",
                    errorPlacement: $.proxy(onError, form),
                    invalidHandler: $.proxy(onErrors, form),
                    messages: {},
                    rules: {},
                    success: $.proxy(onSuccess, form),
                    onfocusout: function (element) { $(element).valid(); }
          },

         

    Summary:

          By default, ASP.NET MVC 3 leverage the famous jQuery validation plug-in to perform client side validation. This famous validation plug-in lazily perform client side validation. Lot of peoples like this behavior but many people do not. In this article, I showed you how you can make the client side validation eager. I am also attaching a sample application. Hopefully you will enjoy this article too.


 

16 Comments

Comments have been disabled for this content.