Displaying Validation Errors with ASP.NET MVC

We all know how important it is to validate user input, but it’s equally important how we present validation errors to the user. Take the following form:


The email field needs to be optional but any address entered must be valid. If a validation error occurs, it should replace the optional label with the error message.

Behind the scenes I’m using Data Annotations to validate the email address, so any errors will be passed into the ModelState. MVC has built-in support for showing these errors (using the ValidateMessageFor helper) so it’s easy to write a wrapper around that, supplying the ‘optional’ text as a parameter.

Here’s an extension method for the HtmlHelper:

public static class ExtensionMethods
    public static MvcHtmlString HelpMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string helpText)
        var validation = htmlHelper.ValidationMessageFor(expression);
        if (validation == null)
            return new MvcHtmlString("<span class='help-inline muted'>" + helpText + "</span>");
            return validation;

Here’s it’s usage:

  <div class="control-group">
        @Html.LabelFor(x => x.EmailAddress, "Email", new { @class = "control-label" })
        <div class="controls">
            @Html.TextBoxFor(x => x.EmailAddress, new { @class = "input-xlarge", placeholder = "Enter an email address" })
            @Html.HelpMessageFor(x => x.EmailAddress, "Optional")
This entry was posted in Tips and Tricks and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s