I have the following viewmodel:
public class ViewModel
{
[Display(Name = "firstname", ResourceType = typeof(Views.Validation))]
public string firstname { get; set; }
[Required(ErrorMessageResourceName="required", ErrorMessageResourceType = typeof(Views.Validation))]
[Display(Name="lastname", ResourceType = typeof(Views.Validation))]
public string lastname { get; set; }
...
}
and my HTML view:
...
<div class="row valid showMsg">
<div class="itemWrap clearfix">
<label>@Html.LabelFor(model => model.firstname)<span class="iconReq"> </span>:</label>
@Html.EditorFor(model => model.firstname)
</div>
<div class="info">
<p class="errorMsg">@Html.ValidationMessageFor(model => model.firstname)</p>
<p class="infoMsg">info message here</p>
<p class="focusMsg">text on active</p>
</div>
</div>
...
If you notice in my HTML view i have a <div class="row valid showMsg"> with a class "showMsg" that controls the display of messages inside my <div class="info">.
Now, for server validation i wrote a custom HTML helper that adds that that class "showMsg" to the div when not valid like so:
public static MvcHtmlString ValidationRowFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
MvcHtmlString normal = html.ValidationMessageFor(expression);
if (normal != null)
{
return MvcHtmlString.Create("errorOn");
}
return null;
}
and use it like so:
<div class="row valid @Html.ValidationRowFor(model => model.firstname)">
I would like to do the same for client validation. So that it would automatically add "showMsg" class to the parent when Error. How would i do it?
Thanks.
Edit: ok this works for regular HTML but not in MVC3 ??
$(function(){
var validator = $(".form").validate({
highlight: function(element) {
$(element).parents().closest('div.row').addClass('errorOn');
},
unhighlight: function(element) {
$(element).parents().closest('div.row').removeClass('errorOn');
}
});
});