jQuery - 如何动态添加验证规则
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3033910/
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 - How to dynamically add a validation rule
提问by Justin
I'm trying to dynamically add a validation rule to some dynamic controls:
我正在尝试向一些动态控件动态添加验证规则:
$("input[id*=Hours]").rules("add", "required");
However this line gives me the following error:
但是这一行给了我以下错误:
$.data(element.form, "validator") is null
$.data(element.form, "validator") 为空
Defining rules the static way with the validate function works fine. What am I doing wrong?
使用 validate 函数以静态方式定义规则工作正常。我究竟做错了什么?
Thanks, Justin
谢谢,贾斯汀
回答by Nick Craver
You need to call .validate()
before you can add rules this way, like this:
您需要先调用,.validate()
然后才能以这种方式添加规则,如下所示:
$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");
The .validate()
documentationis a good guide, here's the blurb about .rules("add", option)
:
该.validate()
文档是一个很好的指南,这是关于.rules("add", option)
:
Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is,
$("form").validate()
is called first.
添加指定的规则并返回第一个匹配元素的所有规则。要求验证父表单,即
$("form").validate()
先调用。
回答by Rick
To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like
要验证所有动态生成的元素,可以向这些元素中的每一个添加一个特殊的类并使用 each() 函数,例如
$("#DivIdContainer .classToValidate").each(function () {
$(this).rules('add', {
required: true
});
});
回答by row1
As well as making sure that you have first called $("#myForm").validate();
, make sure that your dynamic control has been added to the DOM before adding the validation rules.
除了确保您首先调用了$("#myForm").validate();
,还要确保在添加验证规则之前您的动态控件已添加到 DOM。
回答by Peter Jaric
The documentationsays:
文档说:
Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.
添加指定的规则并返回第一个匹配元素的所有规则。要求对父表单进行验证,即首先调用$("form").validate()。
Did you do that? The error message kind of indicates that you didn't.
是你做的吗?错误消息类型表明您没有。
回答by Mohsin
In case you want jquery validate to auto pick validations on dynamically added items, you can simply remove and add validation on the whole form like below
如果您希望 jquery 验证对动态添加的项目自动选择验证,您可以简单地在整个表单上删除和添加验证,如下所示
//remove validations on entire form
$("#yourFormId")
.removeData("validator")
.removeData("unobtrusiveValidation");
//Simply add it again
$.validator
.unobtrusive
.parse("#yourFormId");