gpt4 book ai didi

javascript - Jquery 不显眼的验证 : add class to label of invalid field

转载 作者:行者123 更新时间:2023-12-03 11:50:53 25 4
gpt4 key购买 nike

我在 ASP.NET MVC 项目中使用 jQuery Unobtrusive Validation,并在 ViewModel 中的属性上使用验证属性。

我的表单中的部分 View 包含以下代码:

<div id="contact-form">
<p>
<label for="Name">Name</label>
<span class="field-validation-error" data-valmsg-for="Name" data-valmsg-replace="true"><span for="Name" generated="true" class="">field is required</span></span> <br>
<input class="input-validation-error" data-val="true" data-val-required="field is required" id="Name" name="Name" placeholder="Full Name" type="text" value="">
</p>
</div>

enter image description here

问:如何使用 jQuery 将类添加到无效字段的标签,以便当验证消息出现在标签旁边时,标签也应为红色?

最佳答案

您可以处理模糊事件并检查该值是否有效

$('input[type=text], textarea').blur(function () {
if (!$(this).valid()) {
$(this).prevAll('label').css('color', 'red');
}
});

如果跳过控件,您可能还需要检查提交事件并对每个输入、文本区域等重复相同的操作。

关于javascript - Jquery 不显眼的验证 : add class to label of invalid field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25843358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com