I have a form with several inputs using Html.TextBoxFor and each input has a ValidationMessageFor which gets it's error message from the ViewModel attributes. For this example, we'll pretend there's just one input:
@Html.TextBoxFor(x => x.Code)
@Html.ValidationMessageFor(x => x.Code)
When there's a model error, the validator displays it's error message within a couple of spans which looks like this:
<input type="text" value="" name="Code" id="Code" data-val-required="Personalised code is required" data-val="true" class="input-validation-error">
<span data-valmsg-replace="true" data-valmsg-for="Code" class="field-validation-error">
<span for="Code" generated="true" class="">Personalised code is required</span>
</span>
How do I customise this error message?
For example change the outer span to a div and give both the div and span clases?
<div class="myOuterSpan" data-valmsg-replace="true" data-valmsg-for="Code" class="field-validation-error">
<span class="myInnerSpan" for="Code" generated="true" class="">Personalised code is required</span>
</div>
Or just have one span?
<span class="errorWrapper" for="Code" generated="true">Code is required</span>
Or wrap the whole lot in a div?
<div class="myOuterDiv">
<span data-valmsg-replace="true" data-valmsg-for="Code" class="field-validation-error">
<span for="Code" generated="true" class="">Personalised code is required</span>
</span>
</div>
You get the idea...
THE SOLUTION
I based my solution on Darin's answer and created a CustomValidationMessage, not the customValidationMessageFOR as I was initially intending on creating.
CONTROLLER
ModelState.AddModelError("Code", "Invalid Code");
VIEW
@Html.CustomValidationMessage("Code")
EXTENSION
public static class Extensions
{
public static MvcHtmlString CustomValidationMessage(this HtmlHelper htmlHelper, string modelName)
{
var modelState = htmlHelper.ViewData.ModelState[modelName];
var modelErrors = modelState == null ? null : modelState.Errors;
var modelError = ((modelErrors == null) || (modelErrors.Count == 0))
? null
: modelErrors.FirstOrDefault(e => !string.IsNullOrEmpty(e.ErrorMessage)) ?? modelErrors[0];
if (modelError != null)
{
return MvcHtmlString.Create("<span class='validation_wrapper customValidation'><span>" + modelError.ErrorMessage +"</span></span>");
}
return new MvcHtmlString(string.Empty);
}
}