Adding a container to ValidationSummary helper in ASP.NET MVC

The one thing that is annoying about the validation summary HTML Helper in ASP.NET MVC is that it doesn't render a container element. Problem solved...

The source code below uses an Extension method to append the method ValidationSummaryWithContainer to the HtmlHelper class. This method works by grabbing the actual ValidationSummary first, checking to see if it has output any content, and if it has, wrapping a div element around the generated output. It's pretty simple, but effective.

using System;
using System.Text;

namespace System.Web.Mvc.Html
{
    public static class ValidationSummaryExtension
    {
        /// <summary>
        /// Creates a validation summary with a container element
        /// surrounding the summary and error messages.
        /// </summary>        
        public static string ValidationSummaryWithContainer(this HtmlHelper ext, string message)
        {
            var summaryoutput = ext.ValidationSummary(message);
            if (!string.IsNullOrEmpty(summaryoutput))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<div class='validation-summary-errors-container'>");
                sb.Append(summaryoutput);
                sb.Append("</div>");
                return sb.ToString();
            }
            else
                return string.Empty;
        }
    }
}

To use this helper, on your view page, just call the helper method as you normally would:

<%=Html.ValidationSummaryWithContainer("Please fix the following errors:")%>

If there are no errors, it will render nothing, if there are errors, it will render the output with a containing div element.

<div class='validation-summary-errors-container'>
  <span class="validation-summary-errors">Please fix the following errors:</span>
  <ul class="validation-summary-errors">
    <li>Title is required.</li>
    <li>Description is required.</li>
    <li>Contact email address is required.</li>
    <li>Specific area is required.</li>
    <li>Recaptcha was not valid, please try again.</li>
  </ul>
</div>

Finally, the whole point of this exercise, is so that you can add css style to the containing element and make your error's very pretty.

/*************************************************/
/* VALIDATION ERROR*/

.validation-summary-errors-container
{
    padding: 1.5em;
    margin: .5em 0px .5em 0px;
    background-color: #ffffdf;
    border: 1px solid #df6b6b;
    color: #dc3535;      
}
.field-validation-error
{
    color: #dc3535;
}
.input-validation-error
{
    border: 1px solid #df6b6b;
    background-color: #ffffdf;
}
span.validation-summary-errors
{
    font-weight: bold;
}

Recent comments