I am using MVC 3 validation. My Product Manager wants the label for each control that has an error to turn red.
So 'Student First Name' label should turn red. 'Email address' label should turn red.
I tried to wrap each error msg in a div and check the length of each div
<div id="divValStudentFirstName">@Html.ValidationMessageFor(m => m.studentFirstName)</div>
in a js file:
$(document).ready(function () {
if ($("#divValStudentFirstName").length > 1) {
("#divStudentFirstName").css("color", "red");
}
But I have no success. The validation check is done without a complete refresh and as a result, my $(document).ready isn't fired when validation hits.
Client side validation disabled :
public static IHtmlString ValidationLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText = null) {
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var name = ExpressionHelper.GetExpressionText(expression);
string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? name.Split('.').Last();
if (String.IsNullOrEmpty(resolvedLabelText)) {
return MvcHtmlString.Empty;
}
var tag = new TagBuilder("label");
tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name)));
tag.GenerateId(name);
tag.SetInnerText(resolvedLabelText);
ModelState modelState;
string fullName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (html.ViewData.ModelState.TryGetValue(fullName, out modelState)) {
if (modelState.Errors.Count > 0) {
tag.Attributes.Add("style", "color:red");
}
}
return new MvcHtmlString(tag.ToString());
}
EDIT
Client side validation enabled
I'm really not a king in js, but this seems to work (well on a simple case at least)
$('form').submit(function () {
var form = $(this);
$('label').removeClass('field-validation-error');
if (!form.valid()) {
$('.input-validation-error')
.each(function () {
$("label[for='" + $(this).attr("id") + "']").addClass('field-validation-error');
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With