MVC 3 validation: want my shortcuts to be red that correspond to controls that fail validation

enter image description here

I am using MVC check 3. My product manager wants the label for each control to have an error to turn red.

The Student Name sign should be red. Email must be red.

I tried to wrap each msg error in a div and check the length of each div

<div id="divValStudentFirstName">@Html.ValidationMessageFor(m => m.studentFirstName)</div> 

in js file:

 $(document).ready(function () { if ($("#divValStudentFirstName").length > 1) { ("#divStudentFirstName").css("color", "red"); } 

But I have no success. Validation validation is performed without a full update, and as a result, my $ (document) .ready document does not start when validation is validated.

+6
source share
2 answers

Client side verification is 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 king in js, but it seems to work (well, at least in the simple case)

 $('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'); }); } }); 
+5
source

The following is a jQuery function that will color the containing div tag by adding (or removing) an error class when the submit button is clicked. It can be easily changed to add a class to the label.

  $('form').submit(function () { if ($(this).valid()) { $(this).find('div.form-group').each(function () { if ($(this).find('span.field-validation-error').length == 0) { $(this).removeClass('error-colored'); } }); } else { $(this).find('div.form-group').each(function () { if ($(this).find('span.field-validation-error').length > 0) { $(this).addClass('error-colored'); } }); } }); 
0
source

Source: https://habr.com/ru/post/924785/


All Articles