September 9, 2014 09:33 by
Peter
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 you can see below:
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. ASP.NET MVC 6 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>");
else
return validation;
}
}
Here’s it’s usage:
<fieldset>
<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")
</div>
</div>
</fieldset>