15

I need to wrap the Validation Summary in a div. How do I set the Validation Summary to wrap it with a div when errors are present?

<div class="validation-summary"> 
  <%= Html.ValidationSummary("Login was unsuccessful. Please correct the errors and try again.") %>
</div>

4 Answers 4

25

I had to extend the validation summary extensions in another project of mine to deal with more than one form on a page.

Although this is different, you could create your own extension method...

namespace System.Web.Mvc
{
    public static class ViewExtensions
    {
        public static string MyValidationSummary(this HtmlHelper html, string validationMessage)
        {
            if (!html.ViewData.ModelState.IsValid)
            {
                return "<div class=\"validation-summary\">" + html.ValidationSummary(validationMessage) + "</div>"
            }

            return "";
        }
    }
}

Then just call

<%= Html.MyValidationSummary(
    "Login was unsuccessful. Please correct the errors and try again.") %>

HTHs, Charles

Sign up to request clarification or add additional context in comments.

5 Comments

I get an HtmlHelper does not contain a definition for ValidationSummary when I try and use this in my MVC 2 project - any ideas?
Make sure you have a reference to System.Web.Mvc.Html;
You might want to return a MvcHtmlString instead of a string for the html not to be encoded and to be treated as html code. I am using MVC3 with the new Razor view engine.
Is there a way to make this work for unobtrusive javascript? Since the above code is all server side, it won't work for the client side.
@guanome Sure, you could take away the if (!html.ViewData.ModelState.IsValid) check and just hide an empty/valid validation summary using a different technique, e.g. CSS.
12

What you can do is this :

<%if (!ViewData.ModelState.IsValid) { %>
<div class="validation-summary"> 
    <%= Html.ValidationSummary(
        "Login was unsuccessful. Please correct the errors and try again.") %>
</div>
<% } %>

1 Comment

@çağdaş This doesn't seem to have any effect on client side validation messages. It will hide the error messages if you are using jQuery Validate and Unobtrusive javascript.
5

For MVC 2, ValidationSummary is a extension method, you must add

using System.Web.Mvc.Html;

Comments

1

Use this CSS for li tag for example...

.validation-summary-errors ul li {color:Red;}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.