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 a css element of the message or trigger some javascript?
My code looks like
public static MvcHtmlString ValidationStyledMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, TProperty>> ex)
{
var result = htmlHelper.ValidationMessageFor(ex);
var res = string.Format("<span class=\"required-field\"></span> <span class=\"error required hidden\"><p>{0}<a class=\"close\" href=\"javascript:closeError();\"></a></p></span>", result.ToHtmlString());
return MvcHtmlString.Create(res);
}
As you can see I have a span with a class that is hidden. What I would like to happen is whenever the validation message should be shown I remove the hidden css class.
Any help would be much appreciated.
Here's how you could proceed:
public static MvcHtmlString ValidationStyledMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> 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("<span class=\"required-field\"></span> <span class=\"error required\"><p>{0}<a class=\"close\" href=\"javascript:closeError();\"></a></p></span>", result.ToHtmlString()));
}
return MvcHtmlString.Create(string.Format("<span class=\"required-field\"></span> <span class=\"error required hidden\"><p>{0}<a class=\"close\" href=\"javascript:closeError();\"></a></p></span>", 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:
<script type="text/javascript">
$.validator.setDefaults({
unhighlight: function (element, errorClass, validClass) {
$(element).siblings('span.error').addClass('hidden');
},
highlight: function (element, errorClass, validClass) {
$(element).siblings('span.error').removeClass('hidden');
}
});
</script>