Soe Tun

my attempt to solve common tech problems

  Home  |   Contact  |   Syndication    |   Login
  14 Posts | 0 Stories | 214 Comments | 0 Trackbacks

News

Twitter







Archives

Post Categories

Image Galleries

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

Feedback

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 1/31/2011 9:09 AM float
Hello,

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

Regards,
float

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

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


# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/1/2011 11:41 AM Ismael
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.

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/1/2011 12:23 PM Soe Tun
@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?

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/1/2011 12:23 PM Soe Tun
Is anyone else having the same problem [float] and [Ismael] reported?

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

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/2/2011 7:07 AM Ismael
Well, it was a object oriented design problem specific with client-side validation.

Your post are correctly! Sorry for my false error report.

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/2/2011 2:40 PM Soe Tun
@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.

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/2/2011 4:00 PM Anthony Shaw
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; }



# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/4/2011 6:51 AM prokofyev
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.

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 3/15/2011 12:02 PM Linda
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.

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 3/15/2011 1:48 PM Soe Tun
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 :-(

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 3/30/2011 6:36 AM Matthijs
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

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 3/30/2011 12:28 PM Soe Tun
@Matthijs It is not about client side validation.

It is about how to get the client side Error Messages appear **inside the Validation Summary**.

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 4/11/2011 8:44 AM Mihaela
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?

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 7/10/2011 9:17 PM Vincent
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?



# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 7/12/2011 3:18 PM Soe Tun
@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.

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

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

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 3/1/2012 2:44 AM fatih duman
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

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/19/2013 9:04 AM Jo Van Eyck
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...

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 2/25/2013 5:42 AM sampath
Clean and clear explanation.
Keep it up your good work.

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

# re: ASP.NET MVC 3 Client-Side Validation Summary with jQuery Validation (Unobtrusive JavaScript) 8/15/2014 6:59 PM tom
Great Art!!!! Thank You!

Post A Comment
Title:
Name:
Email:
Comment:
Verification: