Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 validation: want to turn my labels red that correspond to controls that failed validation

enter image description here

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.

like image 489
Dave Alperovich Avatar asked Sep 06 '12 18:09

Dave Alperovich


1 Answers

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');
                });
        }
    });
like image 131
Raphaël Althaus Avatar answered Sep 18 '22 18:09

Raphaël Althaus