Hi have an html helper that allows me to apply a different style to the ValidationForMessage.
My question is how to I tap into the validation event to either change
Here's how you could proceed:
public static MvcHtmlString ValidationStyledMessageFor(this HtmlHelper htmlHelper, Expression> ex)
{
var expression = ExpressionHelper.GetExpressionText(ex);
var modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);
var modelState = htmlHelper.ViewData.ModelState[modelName];
var modelErrors = modelState == null ? null : modelState.Errors;
var modelError = ((modelErrors == null) || (modelErrors.Count == 0))
? null
: modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0];
var result = htmlHelper.ValidationMessageFor(ex);
if (modelError != null)
{
// There was an error => remove the hidden class
return MvcHtmlString.Create(string.Format(" ", result.ToHtmlString()));
}
return MvcHtmlString.Create(string.Format(" ", result.ToHtmlString()));
}
UPDATE:
If you have client side validation enabled you will also need to plug into the jquery validate plugin and manually indicate how to highlight/unhighlight error fields as you have customized the markup. This can be done by simply overriding the default values of the plugin: