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.


 

Published Saturday, April 30, 2011 6:30 AM by imran_ku07

Comments

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Monday, May 2, 2011 9:25 AM by mnmagri

Nice. Really nice. Thanks!

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Tuesday, May 3, 2011 9:40 AM by lycog

Excellent, just a little hack can solve my problem.

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Wednesday, May 11, 2011 7:32 AM by ZSF

Very informative blog for me thank u so much......

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Friday, May 27, 2011 4:48 AM by Saandeshdaddi

Thanks a lot for this informative article.....

Could it be possible for you to write some thing about how things are working in ASP.Net client side validation and how to implement validation for some dependant controls.

e.g. Start date and end date ....etc.

Thank you,

Sandesh Daddi

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Friday, May 27, 2011 6:25 AM by imran_ku07

@Saandeshdaddi,

Unobtrusive Client Side Validation leverage jquery validation library. See docs.jquery.com/.../validation

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Monday, October 17, 2011 4:00 AM by yenni104

Thanks a lot! It solved my problem!

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Thursday, October 20, 2011 2:20 PM by rakeshfrom1985@gmail.com

Very Helpful to me Thanks........

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Tuesday, November 15, 2011 5:18 AM by Caio Pavanelli

Thanks Imran, saved my day!

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Saturday, November 26, 2011 8:09 PM by Kevin

Just what I was looking for, thanks very much.

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Saturday, December 10, 2011 3:06 PM by jamal raja

Thanks Imran for excellent article.

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Tuesday, January 10, 2012 3:27 AM by Ananda Sudarshan ( Anand )

you are just awesome !!!

my requirements were not any of these , but then my validators failed to fire when control lost focus for some reason. tried everything on the stack overflow and asp.net forum none helped me for some reason.

your solution just did the trick

THANKS A LOT :)

Anand

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Wednesday, February 29, 2012 10:49 AM by santosh

can we have validations without DataAnnotations

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Wednesday, February 29, 2012 11:08 AM by imran_ku07

@santosh,

Yes. Check fluent validation, xVal, enterprise library.

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Monday, May 7, 2012 2:19 AM by MADHURITUMATI

Thank you so much Imran...Its working fine

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Tuesday, June 12, 2012 9:25 AM by Bilal

Sometimes when I fill a field that is in error state and move away from it, the field becomes in valid state. However, other fields, stay in error state until I hit submit. Why this behavior?

Thanks

# re: Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation

Tuesday, June 12, 2012 11:11 AM by imran_ku07

@Bilal, I don't see this behaviour.

Thanks for sharing your feedback! If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish - or longer if the blogger is moderating comments.