我为jQuery validate函数的规则创建了for loop
,如下所示:
form.validate({
rules: {
for(var i = 1; i < arguments.length; i++) {
arguments[i]: {required: true,},
}
}
}
但是当我点击提交时,我得到{"error": "Please use POST request"}
(在jsFiddle中)和Uncaught SyntaxError: Unexpected token (
在firebug中。问题可能是最后一个逗号。我通过删除最后一个逗号来遵循Felix和Huangism的建议,但我总是得到同样的错误。
请参阅此jsFiddle。
答案 0 :(得分:6)
它在语法上不正确,你不能创建像字符串连接这样的对象
function x() {
var rules = {};
for (var i = 1; i < arguments.length; i++) {
rules[arguments[i]] = {
required: true
};
}
form.validate({
rules: rules
})
}
答案 1 :(得分:5)
form.validate({
rules: (function() {
results = {}
for(var i = 1; i < arguments.length; i++) {
results[argument[i]] = { required: true }
}
return results;
})();
})
答案 2 :(得分:1)
如何为下面的代码创建规则和消息的循环。
$("#quote").validate({
rules : {
a1_wdad_postcode: {
validatepostcode: true
},
a2_wdad_postcode: {
validatepostcode: true
}
},
messages : {
a1_wdad_postcode: {
validatepostcode: "Postcode is not valid."
},
a2_wdad_postcode: {
validatepostcode: "Postcode is not valid."
}
},
submitHandler: function(form) {