Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display multiple validation errors with @Html.ValidationMessageFor?

I can see that my ModelState.Values[x].Errors is correctly populated with the two validation errors for a single property.

If I use a @Html.ValidationSummary() in my view, it correctly displays both errors.... albeit at the top of the page, and not next to the offending input.

Using @Html.ValidationMessageFor(model => model.MyProperty) displays the first error only for that property!

How do I show both errors, next to the appropriate input?

like image 319
Merenzo Avatar asked Nov 22 '11 07:11

Merenzo


1 Answers

One solution is to implement your own extension method on HtmlHelper that does something different to the default ValidationMessageFor behavior. The sample @Html.ValidationMessagesFor method below will concatenate multiple error messages that have been added to the ModelState during server-side validation (only).

public static MvcHtmlString ValidationMessagesFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
{
    var propertyName = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName;
    var modelState = htmlHelper.ViewData.ModelState;

    // If we have multiple (server-side) validation errors, collect and present them.
    if (modelState.ContainsKey(propertyName) && modelState[propertyName].Errors.Count > 1)
    {
        var msgs = new StringBuilder();
        foreach (ModelError error in modelState[propertyName].Errors)
        {
            msgs.AppendLine(error.ErrorMessage);
        }

        // Return standard ValidationMessageFor, overriding the message with our concatenated list of messages.
        return htmlHelper.ValidationMessageFor(expression, msgs.ToString(), htmlAttributes as IDictionary<string, object> ?? htmlAttributes);
    }

    // Revert to default behaviour.
    return htmlHelper.ValidationMessageFor(expression, null, htmlAttributes as IDictionary<string, object> ?? htmlAttributes);
}

This is useful if you have custom business validation you're applying across a collection belonging to your model (for example, cross-checking totals), or checking the model as a whole.

An example using this, where a collection of Order.LineItems are validated server-side:

@using MyHtmlHelperExtensions    // namespace containing ValidationMessagesFor
@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.LineItems)
    <ul>
        @Html.EditorFor(m => m.LineItems)
    </ul>
    @Html.ValidationMessagesFor(m => m.LineItems)
}
like image 167
Dave A-W Avatar answered Sep 16 '22 12:09

Dave A-W