Javascript 使用类而不是名称值的 jQuery 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2780288/
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 using the class instead of the name value
提问by Matt
I'd like to validate a form using the jquery validate plugin, but I'm unable to use the 'name' value within the html - as this is a field also used by the server app. Specifically, I need to limit the number of checkboxes checked from a group. (Maximum of 3.) All of the examples I have seen, use the name attribute of each element. What I'd like to do is use the class instead, and then declare a rule for that.
我想使用 jquery 验证插件验证表单,但我无法在 html 中使用“名称”值 - 因为这是服务器应用程序也使用的字段。具体来说,我需要限制从一个组中选中的复选框的数量。(最多 3 个。)我见过的所有示例都使用每个元素的 name 属性。我想做的是改用这个类,然后为此声明一个规则。
html
html
This works:
这有效:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="salutation" value="1" />
This doesn't work, but is what I'm aiming for:
这不起作用,但这是我的目标:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" />
javascript:
javascript:
var validator = $(".formToValidate").validate({
rules:{
"salutation":{
required:true,
},
"checkBox":{
required:true,
minlength:3 }
}
});
Is it possible to do this - is there a way of targeting the class instead of the name within the rules options? Or do I have to add a custom method?
是否可以这样做 - 有没有办法在规则选项中定位类而不是名称?还是我必须添加自定义方法?
Cheers, Matt
干杯,马特
回答by Nick Craver
You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:
您可以使用基于该选择器添加规则.rules("add", options),只需从验证选项中删除您想要类的任何规则,并在调用后$(".formToValidate").validate({... });,执行以下操作:
$(".checkBox").rules("add", {
required:true,
minlength:3
});
回答by RicardoS
Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.
另一种方法是使用addClassRules。它特定于类,而使用选择器和 .rules 的选项更通用。
Before calling
打电话之前
$(form).validate()
Use like this:
像这样使用:
jQuery.validator.addClassRules('myClassName', {
required: true /*,
other rules */
});
Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules
参考:http: //docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules
I prefer this syntax for a case like this.
对于这样的情况,我更喜欢这种语法。
回答by Nimeshka Srimal
I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.
我知道这是一个老问题。但我最近也需要同样的一个,我从 stackoverflow 得到了这个问题 + 来自这个博客的另一个答案。博客中的答案更直接,因为它专门针对这种验证。这是如何做到的。
$.validator.addClassRules("price", {
required: true,
minlength: 2
});
This method does not require you to have validate method above this call.
此方法不需要您在此调用上方具有验证方法。
Hope this will help someone in the future too. Source here.
希望这对将来的人也有帮助。来源在这里。
回答by Ajay Sharma
Here's the solution using jQuery:
这是使用jQuery的解决方案:
$().ready(function () {
$(".formToValidate").validate();
$(".checkBox").each(function (item) {
$(this).rules("add", {
required: true,
minlength:3
});
});
});
回答by Delan Azabani
Here's my solution (requires no jQuery... just JavaScript):
这是我的解决方案(不需要 jQuery ... 只需要 JavaScript):
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 4)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
Put this in a script block at the end of <body>and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).
将它放在最后的脚本块中<body>,该代码段将发挥其魔力,将选中的复选框数量限制为最多三个(或您指定的任何数量)。
Here, I'll even give you a test page (paste it into a file and try it):
在这里,我什至会给你一个测试页面(将其粘贴到文件中并尝试):
<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 3)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
</script></body></html>
回答by Farzher
Since for me, some elements are created on page load, and some are dynamically added by the user; I used this to make sure everything stayed DRY.
因为对我来说,有些元素是在页面加载时创建的,有些是由用户动态添加的;我用它来确保一切都保持干燥。
On submit, find everything with class x, remove class x, add rule x.
在提交时,找到类 x 的所有内容,删除类 x,添加规则 x。
$('#form').on('submit', function(e) {
$('.alphanumeric_dash').each(function() {
var $this = $(this);
$this.removeClass('alphanumeric_dash');
$(this).rules('add', {
alphanumeric_dash: true
});
});
});
回答by Barno
If you want add Custom method you can do it
如果你想添加自定义方法,你可以做到
(in this case, at least one checkbox selected)
(在这种情况下,至少选中了一个复选框)
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" onclick="test($(this))"/>
in Javascript
在 JavaScript 中
var tags = 0;
$(document).ready(function() {
$.validator.addMethod('arrayminimo', function(value) {
return tags > 0
}, 'Selezionare almeno un Opzione');
$.validator.addClassRules('check_secondario', {
arrayminimo: true,
});
validaFormRichiesta();
});
function validaFormRichiesta() {
$("#form").validate({
......
});
}
function test(n) {
if (n.prop("checked")) {
tags++;
} else {
tags--;
}
}

