Javascript jQuery 验证 - 将错误类添加到父 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7941662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Validate - Add Error Class to Parent Div
提问by Michael
I am using the jQuery Validate plugin, and can never find a good way to display errors for checkboxes. I'd like to highlight all of the checkbox labels in red if none are selected, and decide to do this by adding an error class to the div that contains the checkboxes and checkbox labels. However, it doesn't seem to be adding the class. Am I not selecting the div correctly?
我正在使用 jQuery Validate 插件,但永远找不到显示复选框错误的好方法。如果没有选择任何复选框,我想以红色突出显示所有复选框标签,并决定通过向包含复选框和复选框标签的 div 添加一个错误类来执行此操作。但是,它似乎并没有添加类。我没有正确选择 div 吗?
HTML:
HTML:
<div class="left-aligned indent">
<label id="id_label" for="id" class="label">Items:</label>
<div class="select-group">
<input type="checkbox" name="items" value="1" id="item_1" />
<label class="checkbox">Item #1</label><br />
<input type="checkbox" name="items" value="1" id="item_2" />
<label class="checkbox">Item #2</label><br />
<input type="checkbox" name="items" value="1" id="item_3" />
<label class="checkbox">Item #3</label><br />
</div>
</div>
Javascript:
Javascript:
$().ready(function() {
$('#addForm').validate({
rules: {
"items": {
required: true,
minlength: 1
}
},
errorPlacement: function(error, element) {
if (element.is(':checkbox')) {
$(this).prev("div").addClass('checkbox-error');
}
else {
return true;
}
}
});
});
CSS:
CSS:
.error {
background-color: #FF898D;
border: 1px solid #000;
}
.checkbox-error {
color: #FF898D;
}
采纳答案by Michael
$(element).parent('div').addClass('checkbox-error');
回答by Luis Evrythng
This should work:
这应该有效:
$('#myform').validate({
highlight: function(element) {
$(element).parent().addClass("field-error");
},
unhighlight: function(element) {
$(element).parent().removeClass("field-error");
}
});
Checkout the documentation for more options:
查看文档以获取更多选项:
回答by KyleMit
From my answer on add class to parent div if validation error occurs using jquery validationbecause I believe it adds value to the existing answers on this question ...
如果使用 jquery 验证发生验证错误,我对add class to parent div 的回答,因为我相信它为这个问题的现有答案增加了价值......
Access Validator Settings
访问验证器设置
The first order of business is to modify the settings
object on your form's validator. You can do this in any of the following ways:
第一个任务是修改settings
表单验证器上的对象。您可以通过以下任一方式执行此操作:
- Before the form is loaded for all forms by calling
jQuery.validator.setDefaults()
- When initializing the form by passing in options on
.validate([options])
- After initialization by locating the validator object on the form with
$("form").data("validator").settings
- 在通过调用为所有表单加载表单之前
jQuery.validator.setDefaults()
- 通过传入选项初始化表单时
.validate([options])
- 通过在表单上定位验证器对象进行初始化后
$("form").data("validator").settings
Since you're using MVC, option #2 is out of the question since unobtrusive-validationwill automatically initialize the form. So let's use option 3 going forward - the goal here is just to be able to customize the settings on the form.
由于您使用的是 MVC,选项 #2 是不可能的,因为非侵入式验证将自动初始化表单。所以让我们继续使用选项 3 - 这里的目标只是能够自定义表单上的设置。
Override Default Behavior
覆盖默认行为
The default methods we'll want to modify are highlight
and unhighlight
which will highlightinvalid fields or revert changes made by the highlight option, respectively. Here's their default behavior according to the source code:
我们要修改的默认方法是highlight
和unhighlight
,它们将分别突出显示无效字段或恢复由 highlight 选项所做的更改。根据源代码,这是他们的默认行为:
highlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
},
unhighlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
} else {
$( element ).removeClass( errorClass ).addClass( validClass );
}
}
So you have a couple options here as well.
所以你在这里也有几个选择。
- Completely replace those functions and write them on your own
- Wrap those functions and call them like normal but add your own custom code before or after.
- 完全替换那些函数,自己写
- 包装这些函数并像往常一样调用它们,但在之前或之后添加您自己的自定义代码。
Option 1 - Replace Wholesale
选项 1 - 更换批发
This route is pretty easy. Just write whatever you want in there. Maybe seed from the source code, maybe do your own thing.
这条路线很容易。随便在里面写什么就行。也许来自源代码的种子,也许做你自己的事情。
var valSettings = $("form").data("validator").settings
valSettings.highlight = function(element, errorClass, validClass) { ... }
valSettings.unhighlight = function(element, errorClass, validClass) { ... }
Option 2 - Wrap Functions
选项 2 - 包装函数
This is less intrusive so probably preferable in most cases.
这不太具有侵入性,因此在大多数情况下可能更可取。
Since ultimately you will be replacing the value of valSettings.highlight
, you'll need access to a clean pristine version of the original function. You can save your own or grab one off the global defaults
由于最终您将替换 的值valSettings.highlight
,因此您需要访问原始函数的干净原始版本。您可以保存自己的或从全局默认值中获取一个
// original highlight function
var highlightOriginal = $("form").data("validator").settings.highlight;
var highlightDefaults = $.validator.defaults.highlight
In terms of wrapping JavaScript functions, there are a couple examples here, here, and here). Here's a parsed down example from one of those, that will help bind this
context across function calls, preserve the arity of the arguments being passed, and persist the return value:
在包装的JavaScript函数而言,有一对夫妇的例子在这里,在这里,和这里)。这是其中一个的解析示例,它有助于this
跨函数调用绑定上下文,保留传递的参数的数量,并保留返回值:
function wrap(functionToWrap, beforeFunction) {
return function () {
var args = Array.prototype.slice.call(arguments),
beforeFunction.apply(this, args);
return functionToWrap.apply(this, args);
};
};
Then you'll also have to quickly define whatever additional behavior you want to fire whenever the call is made. In this case, let's find the closest parent div
to the element and update it's classes like this:
然后,您还必须快速定义每次调用时要触发的任何其他行为。在这种情况下,让我们找到离div
元素最近的父元素并像这样更新它的类:
function highlightDecorator(element, errorClass, validClass) {
$(element).closest("div").addClass(errorClass).removeClass(validClass);
}
Wrapping It All Up(see what I did there)
把它全部包起来(看看我在那里做了什么)
$(function () {
var valSettings = $("form").data("validator").settings
valSettings.highlight = wrap($.validator.defaults.highlight, highlightDecorator)
valSettings.unhighlight = wrap($.validator.defaults.unhighlight, unhighlightDecorator)
});
function wrap(functionToWrap, beforeFunction) {
return function () {
var args = Array.prototype.slice.call(arguments);
beforeFunction.apply(this, args);
return functionToWrap.apply(this, args);
};
};
function highlightDecorator(element, errorClass, validClass) {
$(element).closest("div").addClass(errorClass).removeClass(validClass);
}
function unhighlightDecorator(element, errorClass, validClass) {
$(element).closest("div").addClass(validClass).removeClass(errorClass);
}
So when we combine all of the above functions, it should look something like this:
因此,当我们组合上述所有功能时,它应该看起来像这样:
Working Demo in Stack Snippets and jsFiddle
Stack Snippets 和jsFiddle 中的工作演示
$(function () {
var valSettings = $("form").data("validator").settings
valSettings.highlight = wrap($.validator.defaults.highlight, highlightDecorator)
valSettings.unhighlight = wrap($.validator.defaults.unhighlight, unhighlightDecorator)
});
function wrap(functionToWrap, beforeFunction) {
return function () {
var args = Array.prototype.slice.call(arguments);
beforeFunction.apply(this, args);
return functionToWrap.apply(this, args);
};
};
function highlightDecorator(element, errorClass, validClass) {
$(element).closest("div").addClass(errorClass).removeClass(validClass);
}
function unhighlightDecorator(element, errorClass, validClass) {
$(element).closest("div").addClass(validClass).removeClass(errorClass);
}
input.input-validation-error {
border: solid 1px red;
}
.input-validation-error label {
color: red;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<form action="/Person" method="post">
<div class="required">
<label for="Name">Name <em>*</em></label>
<input id="Name" name="Name" type="text" value=""
data-val="true" data-val-required="The Name field is required."/>
<span class="field-validation-valid"
data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>
<input type="submit" value="Save" />
</form>