ASP.NET MVC with JQuery Validation and ValidationSummary

     Introduction:

          One of the great feature of ASP.NET MVC 2 is the support of client side validation. Client side validation in ASP.NET MVC 2 is possible with ASP.NET Ajax(MicrosoftMvcValidation.js) and jQuery(MicrosoftMvcJQueryValidation.js) libraries. Both ASP.NET Ajax and jQuery works well. When you use ASP.NET Ajax client side validation in ASP.NET MVC, Html ValidationSummary helper will display validation errors when invalid form is submitted but when you use jQuery client side validation in ASP.NET MVC, Html ValidationSummary helper will not display validation errors when invalid form is submitted. In this article I will show you how to make it possible to display validation errors when invalid form is submitted in ValidationSummary when you are using jQuery client side validation.

 

    Description:

          Let's create a sample application to demonstrate this. First of all create an ASP.NET MVC application. Then just open HomeController.cs and add the following code,

 

        public ActionResult Index()
        {
            return View();
        }
        
        [HttpPost]
        public ActionResult Index(Student s)
        {
            if(!ModelState.IsValid)
                return View();
            return Content("Thank you for submitting your form");
        }

 

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

 

    public class Student
    {
            [Required]
            public string Name { get; set; }

            [Required, Range(0, 200)]
            public int? Age{ get; set; }
    }

 

          Next add a view for Index action and add the following lines inside this view,

 

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ValidationSummaryAndJqueryValidation.Models.Student>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <% Html.EnableClientValidation();%>        
    <%using(Html.BeginForm()){ %>
    <%: Html.ValidationSummary() %>
        <table>
        <tr>
            <td>
                Name:
            </td>
            <td>
                <%: Html.TextBoxFor(a => a.Name)%>
            </td>
            <td>
                <%: Html.ValidationMessageFor(a => a.Name)%>
            </td>
        </tr>
        <tr>
            <td>
                Subject:
            </td>
            <td>
                <%: Html.TextBoxFor(a => a.Age)%>
            </td>
            <td>
                <%: Html.ValidationMessageFor(a => a.Age)%>
            </td>
        </tr>
        <tr>
            <td colspan="3" align="center">
                <input type="submit" />
            </td>
        </tr>
    </table>
    <%} %>
</asp:Content>

 

         Now let's first add the necessary ASP.NET Ajax script files for validation in Site.Master,

 

<script src="<%=Url.Content("~/Scripts/MicrosoftAjax.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/MicrosoftMvcAjax.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/MicrosoftMvcValidation.js")%>" type="text/javascript"></script>

 

         Now just run this application. You will find the following screen,

 

        

 

         This shows that ValidationSummary is work as expected if you use ASP.NET Ajax validation. Now just replace the above script files with jQuery script files for validation in Site.Master,

 

<script src="<%=Url.Content("~/Scripts/jquery-1.4.1.min.js")%>"type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/MicrosoftMvcJQueryValidation.js")%>" type="text/javascript"></script>

 

         Now just run this application again. You will find the following screen,

 

         


 

         This shows that ValidationSummary is not display validation errors if you use jQuery validation script files. To make it work just open MicrosoftMvcJQueryValidation.js and replace,

 

	errorClass: "input-validation-error",

 

         with

 

        invalidHandler: function (form, validator) {            
            var ul = $("#validationSummary ul");
            if (ul.length > 0) {
                $("#validationSummary").addClass("validation-summary-errors");
                $("#validationSummary").removeClass("validation-summary-valid");
                ul.html("");                
                for (var name in validator.errorList)
                    ul.append("<li>" + validator.errorList[name].message + "</li>")
            }
        },
        errorClass: "input-validation-error",

 

         The above code simply display ValidationSummary with validation errors when invalidHandler event is fired. The invalidHandler event is fired when an invalid form is submitted. Now save MicrosoftMvcJQueryValidation.js file and run again your application you will find that ValidationSummary will work as expected. If you need to process something when the form is valid, you can handle submitHandler event in the same way.

 

    Summary:

          ValidationSummary HTML helper is used to displays a summary of all validation errors. But ValidationSummary not shows validation errors when you use it with jQuery client side validation. So in this article I showed how to display validation errors in ValidationSummary when you are using jQuery client side validation. I showed this with an example. I am also attaching a sample application. Hope you will enjoy this article too.

12 Comments

  • Nice post. Are there any dis-advantages of using ASP.NET AJAX vs. jQuery over here other than the additional overhead of including the ASP.NET AJAX scripts? (assuming of course that you have already included jquery)

  • Too bad none of this stuff works if you are running your data access through an out-of-process service call. Yes, I suppose I could decorate the generated proxy classes on the client side, but that kind of defeats the purpose because I still have to do the validation on the server-side in case someone manages to bypass my UI or I have third-party companies generating their own proxies.

  • I don't have MicrosoftMvcJQueryValidation.js in my MVC 2.0 project. Care to relinguish its secret location?

  • @Eric,
    Just Download the attached Project.

  • @Eric,

    Make sure that the sequence in which you include the script is correct. That can be the only explanation for the missing method. Or your JS file(s) is somehow corrupt.

    Cheers,

    Imran Rashid.

  • Very nice article.

    Thnks for sharing

  • Hi,

    just curious if this can apply to asp.net form? leveraging data annotation that is applied to an class' property.

  • @Eric,
    You can use it with ASP.NET Dynamic Data,
    http://rachelappel.com/asp-net-dynamic-data/custom-validation-in-asp-net-dynamic-data-using-attributes/

  • Nice article on how to properly get the validation summary to show up. However, your modification fails to take into account the excludePropertyErrors parameter of Html.ValidationSummary. I have extended your code to include evaluation of whether to show field errors or not along with the summary. Replace invalidHandler with this

    invalidHandler: function (form, validator) {
    var ul = $("#validationSummary ul");
    if (ul.length > 0) {
    $("#validationSummary").addClass("validation-summary-errors");
    $("#validationSummary").removeClass("validation-summary-valid");
    if (validationContext.ReplaceValidationSummary) {
    ul.html("");
    for (var name in validator.errorList)
    ul.append("" + validator.errorList[name].message + "")
    }
    }
    }

  • hi,
    I used Unobtrusive JQuery at client side to validate error.
    My understanding is that server side will not hit if validation on client side fails. but in my application server always hits even if validation fails in client side. Is it right? If no, could you tell me how to fix it?

    config file:




    Include script files:

    .Add("~/Scripts/jquery-1.6.2.min.js")
    .Add("~/Scripts/jquery.unobtrusive-ajax.min.js")
    .Add("~/Scripts/jquery.validate.min.js")
    .Add("~/Scripts/jquery.validate.unobtrusive.min.js")

    MetaData:

    [MetadataType(typeof(EPRMetaData))]
    public partial class EPR { }
    public class EPRMetaData
    {
    public Int32 Id;
    [DisplayName("EPR_ID"), Required]
    [StringLength(10,ErrorMessage="Field EPR_ID can't exceed 10 characters.")]
    public String HP_EPR_ID { get; set; }
    }
    Note that I think validation StringLength will be executed via Jquery.

  • @colson see this,

    http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx

  • @Rakesh, You need custom validation summary. Please google.

Comments have been disabled for this content.