How to display MVC 3 client side validation results in validation summary

b3n picture b3n · Mar 1, 2011 · Viewed 36.7k times · Source

I have a registration form on which I use client side validation (Required, StringLength etc. specified on my view model). The form is currently pretty much how the scaffolder creates it:

@using (Html.BeginForm("Index", "Registration"))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Registration details</legend>
        @Html.ValidationSummary(false, "Please correct these errors:")
        @Html.ValidationMessageFor(model => model.Username)
        <div class="editor-label">
            @Html.LabelFor(model => model.Username)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Username)
        </div>
        <p>
            <input type="submit" value="Register" />
        </p>
    </fieldset>
}

The only difference is that I moved the ValidationMessageFor to the top right beneath the ValidationSummary.

What I would like to do is display the client side validation errors in the validation summary. Currently they are just displayed on top of the form but not using the validation summary. How can I display client side validation errors using the validation summary? Is this even possible?

Update

Darin I have used your code in a new project and this is what it looks like for me when the client side validation kicks in:

Client side validation http://tinypic.com/images/404.gif

I expected this to be shown IN the validation summary with the validation summary styles applied. I also submitted the form which then look like this:

After submit

Thanks,

b3n

Answer

orcy picture orcy · May 21, 2011

This article seems to explain how add client side validation summary into the validation summary:

http://geekswithblogs.net/stun/archive/2011/01/28/aspnet-mvc-3-client-side-validation-summary-with-jquery-validation-unobtrusive-javascript.aspx

However I did not test it by myself and it does not seem to have any difference with your code. If it does not work a good point to look might be jquery.validate.unobtrusive.js file on a function that actually places validation errors:

function onErrors(form, validator) {  // 'this' is the form element
    var container = $(this).find("[data-valmsg-summary=true]"),
        list = container.find("ul");

    if (list && list.length && validator.errorList.length) {
        list.empty();
        container.addClass("validation-summary-errors")
          .removeClass("validation-summary-valid");

        $.each(validator.errorList, function () {
            $("<li />").html(this.message).appendTo(list);
        });
    }
}