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>
craigmoliver
  • 6,499
  • 12
  • 49
  • 90

4 Answers4

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

Charlino
  • 15,802
  • 3
  • 58
  • 74
  • 4
    I get an HtmlHelper does not contain a definition for ValidationSummary when I try and use this in my MVC 2 project - any ideas? – Slee Mar 26 '10 at 19:30
  • 4
    Make sure you have a reference to System.Web.Mvc.Html; – ajbeaven Dec 08 '10 at 00:17
  • 4
    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. – Jason Apr 25 '11 at 14:19
  • 2
    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. – FarFigNewton May 04 '12 at 14:47
  • @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. – Charlino May 09 '12 at 16:10
  • @Charlino That sounds just too easy. Thanks! – FarFigNewton May 09 '12 at 18:08
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>
<% } %>
Çağdaş Tekin
  • 16,592
  • 4
  • 49
  • 58
  • @ç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. – FarFigNewton May 04 '12 at 14:46
5

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

using System.Web.Mvc.Html;
Chal92
  • 59
  • 1
  • 1
1

Use this CSS for li tag for example...

.validation-summary-errors ul li {color:Red;}
NoWar
  • 36,338
  • 80
  • 323
  • 498