jQuery Validation Plugin - 添加适用于多个字段的规则
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8829030/
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 Validation Plugin - adding rules that apply to multiple fields
提问by benino
I'm using the jQuery Validationplugin:
我正在使用jQuery 验证插件:
I have several fields in a large form that I want to apply the same rules to. I've simplified the code for this example. This code doesn't work, but I want to do something like this. The second rule should apply to both first_name
and last_name
. I want to encapsulate all the rules here in this function and not edit the class lists of some of the form elements to add a required class or whatever.
我有几个大格式的字段,我想对其应用相同的规则。我已经简化了这个例子的代码。这段代码不起作用,但我想做这样的事情。第二条规则应该同时适用于first_name
和last_name
。我想把这里的所有规则都封装在这个函数中,而不是编辑一些表单元素的类列表来添加所需的类或其他什么。
(Again, I have several different groups of form fields with different requirements that I want to group. I only put required: true
in that element for simplicity)
(同样,我有几组具有不同要求的表单字段,我想对其进行分组。required: true
为了简单起见,我只放入了该元素)
$('#affiliate_signup').validate(
{
rules:
{
email: {
required: true,
email: true
},
first_name,last_name: {
required: true
},
password: {
required: true,
minlength: 4
}
}
});
Thanks in advance.
提前致谢。
回答by Sparky
For the purposes of my example, this is the base starting code:
就我的示例而言,这是基本的起始代码:
HTML:
HTML:
<input type="text" name="field_1" />
<input type="text" name="field_2" />
<input type="text" name="field_3" />
jQuery:
jQuery:
$('#myForm').validate({
rules: {
field_1: {
required: true,
number: true
},
field_2: {
required: true,
number: true
},
field_3: {
required: true,
number: true
}
}
});
Option 1a)You can pull out the groups of rules and combine them into common variables.
选项 1a)您可以提取规则组并将它们组合成公共变量。
var ruleSet1 = {
required: true,
number: true
};
$('#myForm').validate({
rules: {
field_1: ruleSet1,
field_2: ruleSet1,
field_3: ruleSet1
}
});
Option 1b)Related to 1a above but depending on your level of complexity, can separate out the rules that are common to certain groups and use .extend()
to recombine them in an infinite numbers of ways.
选项 1b)与上述 1a 相关,但取决于您的复杂程度,可以分离出某些组共有的规则,并.extend()
以无限多种方式将它们重新组合。
var ruleSet_default = {
required: true,
number: true
};
var ruleSet1 = {
max: 99
};
$.extend(ruleSet1, ruleSet_default); // combines defaults into set 1
var ruleSet2 = {
min: 3
};
$.extend(ruleSet2, ruleSet_default); // combines defaults into set 2
$('#myForm').validate({
rules: {
field_1: ruleSet2,
field_2: ruleSet_default,
field_3: ruleSet1
}
});
End Result:
最终结果:
field_1
will be a required number no less than 3.field_2
will just be a required number.field_3
will be a required number no greater than 99.
field_1
将是一个不小于 3 的必需数量。field_2
将只是一个必需的数字。field_3
将是不大于 99 的必需数字。
Option 2a)You can assign classes to your fields based on desired common rules and then assign those rules to the classes. Using the addClassRules
method we're taking compound rules and turning them into a class name.
选项 2a)您可以根据所需的通用规则为您的字段分配类,然后将这些规则分配给类。使用该addClassRules
方法,我们将复合规则转化为类名。
HTML:
HTML:
<input type="text" name="field_1" class="num" />
<input type="text" name="field_2" class="num" />
<input type="text" name="field_3" class="num" />
jQuery:
jQuery:
$('#myform').validate({ // initialize the plugin
// other options
});
$.validator.addClassRules({
num: {
required: true,
number: true
}
});
Option 2b)The main difference from option 2a is that you can use this to assign rules to dynamically created input elements by calling rules('add')
method immediately after you create them. You coulduse class
as the selector, but it's not required. As you can see below, we've used a wildcard selector instead of class
.
选项 2b)与选项 2a 的主要区别在于,您可以使用它来为动态创建的输入元素分配规则,rules('add')
方法是在创建它们后立即调用方法。您可以使用class
作为选择,但它不是必需的。正如您在下面看到的,我们使用了通配符选择器而不是class
.
The .rules()
method mustbe called any time afterinvoking .validate()
.
调用后必须随时调用该.rules()
方法。.validate()
jQuery:
jQuery:
$('#myForm').validate({
// your other plugin options
});
$('[name*="field"]').each(function() {
$(this).rules('add', {
required: true,
number: true
});
});
Documentation:
文档:
回答by Antonio Clemente
You can use the 'getter' syntax in this way:
您可以通过以下方式使用“getter”语法:
{
rules:
{
email: {
required: true,
email: true
},
first_name: {
required: true
},
get last_name() {return this.first_name},
password: {
required: true,
minlength: 4
}
}
}
回答by alpham8
If I understood you right, you want to apply many rules to many fields, that may differ at some rules, but you are too lazy to repeat yourself with the same rules to other fields. However, with jQuery validate it's possible to have more than one rule on one input field. Just use the array notation here.
如果我理解正确,您想将许多规则应用于许多领域,可能在某些规则上有所不同,但是您懒得将相同的规则重复到其他领域。然而,使用 jQuery 验证,一个输入字段可能有多个规则。只需在此处使用数组表示法。
To achieve your use case, just add data
attributes to each input field with the rules you want to apply to it. In best case, use an url encoded json format, so that you just need one data
attribute per each input field. E. g.:
要实现您的用例,只需将data
属性添加到每个输入字段,并使用您要对其应用的规则。在最好的情况下,使用 url 编码的 json 格式,这样data
每个输入字段只需要一个属性。例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>validate test</title>
</head>
<body>
<form id="myForm" name="myForm" method="post" action="www.example.com/my-url">
<input type="text" name="txt1" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
<input type="text" name="txt2" data-rules="%7B%22required%22%3Atrue%2C%22minlength%22%3A2%2C%22maxlength%22%3A10%7D" />
<input type="number" name="number1" data-rules="%7B%22required%22%3Atrue%2C%22number%22%3Atrue%2C%22min%22%3A1%2C%22max%22%3A999%7D" />
<input type="email" name="email1" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
<input type="email" name="email2" data-rules="%7B%22required%22%3Atrue%2C%22email%22%3Atrue%2C%22minlength%22%3A20%7D" />
</form>
<script type="text/javascript">
var $field = null;
var rules = {};
$('#myForm input, #myForm textarea').each(function (index, field) {
$field = $(field);
rules[$field.attr('name')] = JSON.parse(decodeURIComponent($field.attr('data-rules')));
});
$('#myForm').validate(rules);
</script>
</body>
</html>
The basic technology behind that is simple:
其背后的基本技术很简单:
- Create your fields with the `data-`` attribute.
- Loop over each input field to grab the rules that you want to apply on it.
- Apply your collected rules to the form element
- 使用 `data-` 属性创建你的字段。
- 循环遍历每个输入字段以获取要对其应用的规则。
- 将收集到的规则应用于表单元素
You could also use input groups with the same validators that way, e. g. by using classes for it and predefined JavaScript variables with the rules object. I think you got the idea on how to get lazy in an elegant way ;-)
您还可以以这种方式使用具有相同验证器的输入组,例如通过为它使用类和带有规则对象的预定义 JavaScript 变量。我想你知道如何以优雅的方式变得懒惰;-)