Geeks With Blogs
Soe Tun my attempt to solve common tech problems

When we were working with ASP.NET MVC 2, we needed to write our own JavaScript to get Client-Side Validation Summary with jQuery Validation plugin.
I am one of those unfortunate people still stuck with .NET Framework Runtime 2.0 and .NET Framework 3.5; meaning I am still on ASP.NET MVC 2.
So I will still keep on supporting by answering any question you may have with my original code.

 

Long awaited ASP.NET MVC 3 has been released, and it supports Client Side Validation Summary with jQuery out-of-the-box with new features like Unobtrusive JavaScript.

 

1. _Layout.cshtml Template

Notice that I am using Protocol Relative URLs ( i.e., '//'.  Not 'http://' or 'https://' ) to reference script files and css files and you should use it too like that!
However, please note that IE7 and IE8 will download the CSS files twice so use it with judgement.

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Assets/Site.css")"  rel="stylesheet" type="text/css" />
    <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" media="screen" />
</head>

<body>
    @RenderBody()

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"           type="text/javascript"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"      type="text/javascript"></script>
    <script src="//ajax.aspnetcdn.com/ajax/jQuery.Validate/1.7/jQuery.Validate.min.js" type="text/javascript"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
</body>
</html>

 

2. MVC View Template

There are 3 things you *must* do exactly to get Client Side Validation Summary working.

  1. You must declare your Validation Summary **inside** the `Html.BeginForm()` block like below.
  2. You must pass `excludePropertyErrors: false` to the  Html.ValidationSummary()  method.
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(false, "Please fix these errors.");
    
        <!-- The rest of your View Template -->
    
    }
    Html.ValidationSummary(false, "Please fix these errors.") generates the HTML code below.
    <div class="validation-summary-valid" data-valmsg-summary="true">
        <span>Please fix these errors.</span>
        <ul><li style="display:none"></li></ul>
    </div>
    If you look into the jquery.validation.unobtrusive.js source code, you will understand why I said the Validation Summary declaration must be inside the Html.BeginForm( ) block.
    On line #56 inside the function onErrors(form, validator) { // 'this' is the form element function, it retrieves the validation summary HTML node like below.
    var container = $(this).find("[data-valmsg-summary=true]")
    Basically, it looks for the validation summary HTML node **inside** the corresponding <form> tag.
    If you don't declare the validation summary block using Html.ValidationSummary(false, "Please fix these errors.") using the false parameter, the data tag data-valmsg-summary="true" does NOT get generated, and the jQuery Validation Unobtrusive library won't be able to locate your validation summary to populate the error messages.
    This is needed because you may have multiple <form> tags on the entire page and the validation library needs to know exactly which validation summary block to insert the client-side validation error messages.
     
  3. You have to put the following two elements in the `<appSettings />` block of your Web.config file.
    <add key="ClientValidationEnabled"      value="true"></add>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"></add>


 

3. CSS Styles for Validation

As Anthony mentioned below in the comments, I forgot to mention about the CSS styles used by MVC framework for validation display.
The CSS class names below are pretty self-explanatory of what they do.

.input-validation-error { border: 1px solid #f00 }
.input-validation-valid  { /* Optional: you can set whatever style you want */ }
.field-validation-error { color: #f00 }
.field-validation-valid { display: none }
.validation-summary-errors { font-weight: bold; color: #f00 }
.validation-summary-valid { display: none }

 That is all you need to do.  Simple, right? 


P.S:
Without getting into too much technical details, I just wanted to let you know what I went through to get this to work.
I had to look into the ASP.NET MVC 3 RTM Source Code and the jquery.validate.unobtrusive.js source.

Initially, I thought I have to hack the jquery.validate.unobtrusive.js or something to get this to work.
But after digging into MVC3 RTM source, I found out how to do it.

 

3. Sample Project Download

Please let me know if you cannot download the Sample project from my SkyDrive.

 

Update:

July 12th 2011: elaborated why you have to declare the Validation Summary block inside the <form> tag due to Vincent's comment below.

Posted on Friday, January 28, 2011 2:31 PM MVC , jQuery , jQueryValidation | Back to top


Comments on this post: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Hello,

the summary doesn't work right. IE8 and Firefox are displaying the summary message even when nobody pressed the submit button.

Regards,
float
Left by float on Jan 31, 2011 9:09 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
@float
I'm not having this problem at all.
I'll upload my sample project, and please try it out.
Left by Soe Tun on Jan 31, 2011 3:06 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
When i run your project and press on edit, i see the error message too.
Left by float on Feb 01, 2011 3:01 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Está funcionando perfeitamente sem a necessidade de ter feito nada em especial.

Porém, o que está acontecendo é o seguinte:
# The Id field is required.

Isso só acontece client-side, no server-side continua funcionando normalmente.

Gostaria de saber como resolver isso, porque achei muuuuito bom a solução.
Left by Ismael on Feb 01, 2011 11:41 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
@float
Can you please take a screenshot of what you are seeing? Also, please check if you have some kind of JavaScript error or something using IE's


@Ismael
Pode você por favor, descreva o que você quer dizer com "# O campo ID é necessária."?
Isso é uma mensagem de erro do lado do cliente que você está vendo?
Left by Soe Tun on Feb 01, 2011 12:23 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Is anyone else having the same problem [float] and [Ismael] reported?
Left by Soe Tun on Feb 01, 2011 12:23 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
I don't know why, but now your sample project it works right.
Left by float on Feb 02, 2011 4:15 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Well, it was a object oriented design problem specific with client-side validation.

Your post are correctly! Sorry for my false error report.
Left by Ismael on Feb 02, 2011 7:07 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
@float
Maybe the JavaScript files referenced from the CDNs were not getting downloaded properly by your browser.


Anyway, thanks to both [@float] and [@Ismael] for trying it out and letting me know that it works fine.
Left by Soe Tun on Feb 02, 2011 2:40 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
When using Client Side Validation, it changes the css class from validation-summary-valid to validation-summary-errors. I found a fix was to add the following to my main css file

.validation-summary-valid { display: none; }

Left by Anthony Shaw on Feb 02, 2011 4:00 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Thank you very much for hinting what unobtrusive validation tags are rendered only after calling Html.BeginForm() method. I wasn't able to understand why client side scripts didn't work on my page which was similar to tutorial's one. Though it had <form> tag instead.
Left by prokofyev on Feb 04, 2011 6:51 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Thank you for writing this tutorial.

I've read a few today; but none of the slight differences have helped me to get mine working. In short, my client side validation isn't triggered until after the form is submitted. Afterward it works fine. Do you have any insight on this problem?

thanks again.
Left by Linda on Mar 15, 2011 12:02 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Hi Linda,

yes I noticed that too. It used to trigger ASAP when we were using the original technique.
Now with Unobtrusive Javascript mode, it only triggers when the user clicks on the 'submit' button.

I think it is because of how the jquery.validate.unobtrusive.min.js registers with the jQuery Validation callback method.
I'm sorry I can't do anything about it unless you go back to the MVC2 style from my previous blog post :-(
Left by Soe Tun on Mar 15, 2011 1:48 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
I thought that client side validation is also out of the box in MVC 2. You just have to add <%: Html.EnableClientVerification() %>. In MVC3 this is default on, that's all.

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
Left by Matthijs on Mar 30, 2011 6:36 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
@Matthijs It is not about client side validation.

It is about how to get the client side Error Messages appear **inside the Validation Summary**.
Left by Soe Tun on Mar 30, 2011 12:28 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
What about the case when you returning a form with Ajax call on the main page. How to handle Server Validation Errors when posting a form?
Left by Mihaela on Apr 11, 2011 8:44 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
2. MVC View Template

There are 3 things you *must* do exactly to get Client Side Validation Summary working.

(1) You must declare your Validation Summary **inside** the `Html.BeginForm()` block like below.
(2) You must pass `excludePropertyErrors: false` to the Html.ValidationSummary() method.

Why the mvc default template LogOn page declare this out of the form but still working?

Left by Vincent on Jul 10, 2011 9:17 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
@Vincent

I have explained why I am declaring the Validation Summary inside the Html.BeginForm( ) block.
I may be wrong, but I am too lazy **he he :-D** to test it out on in my own project to see why it is working for you on the LogOn page.
Left by Soe Tun on Jul 12, 2011 3:18 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Thank you! It worked for me ! Keep on posting good stuff ;) !
Left by Dannz on Oct 28, 2011 5:39 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
why false I still do not understand it will never work with false
or share complete working sample
Left by aay on Dec 11, 2011 8:54 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
hi,
how can i use this validation with button click? i dont want to do with submit,i use jquery functions for insert-update.
thanks
Left by fatih duman on Mar 01, 2012 2:44 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Thanks for this post! I was trying to get the ValidationSummary to play nicely with jQuery Validation for hours, without much success. With your post, I had it up and running in 5 minutes.

It seems nearly impossible to combine jQuery Validation with live checking (on change of input instead of on form submit) and a ValidationSummary...
Left by Jo Van Eyck on Feb 19, 2013 9:04 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Clean and clear explanation.
Keep it up your good work.
Left by sampath on Feb 25, 2013 5:42 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Great Example......I was tried from last 3 days ,Now finally i got success with this Article.....Thanks...
Left by kapil on May 19, 2014 7:42 AM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
Great Art!!!! Thank You!
Left by tom on Aug 15, 2014 6:59 PM

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript)
Requesting Gravatar...
shgh sh gh sthsth th t syt
Left by hfhd on Apr 28, 2015 2:24 AM

Your comment:
 (will show your gravatar)


Copyright © Soe Tun | Powered by: GeeksWithBlogs.net | Join free