我正在使用jQuery的验证,可在此处找到:http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules
我目前设置了一些“自定义”规则:
else if(valID =="#shipForm")
{
$("#fName").rules("add",{regexName: "^[a-zA-Z]+(([\'\-][a-zA-Z])?[a-zA-Z]*)*$",minlength: 2,messages:{minlength:"Must be 2 characters."}});
$("#lName").rules("add",{regexName: "^[a-zA-Z]+(([\'\-][a-zA-Z])?[a-zA-Z]*)*$",minlength: 2,messages:{minlength:"Must be 2 characters."}});
$("#sAdd1").rules("add",{stringCheck: "",minlength:2,messages:{minlength:"Enter your complete street address."}});
$("#sAdd2").rules("add",{stringCheck: ""});
$("#city").rules("add",{stringCheck: "",minlength:2,messages:{minlength:"Enter the full name of your city"}});
$("#zipcode").rules("add",{stripZip: ""});
$("#phoneIn").rules("add",{stripPhone: "",maxlength:15,messages:{maxlength:"Phone number exceeds allowed length"}});
$("#altPhone").rules("add",{stripPhone: ""});
$("#state").rules("add",{checkMenu: ""});
$("#country").rules("add",{checkMenu: ""});
}
我希望做的是...将.rules抽象出来并能够从函数中获取它们。我的问题是它们不仅仅是字符串,所以我不知道如何从另一个函数中获取信息并填充.rules(“规则的传递值”)
这不起作用,但这是我有点希望的一个例子
function getRule(rule)
{
switch (rule)
{
case "fName":
return "\"add\",{regexName: \"^[a-zA-Z]+(([\'\-][a-zA-Z])?[a-zA-Z]*)*$\",minlength: 2,messages:{minlength:\"Must be 2 characters.\"}}";
break;
}
}
但我显然不能将一个字符串传回并将其运回.rules。
有什么想法吗?
答案 0 :(得分:1)
您可以返回一个对象
function getRule(rule)
{
switch (rule)
{
case "fName":
return {
param1 : "add",
param2 : {
regexName: "^[a-zA-Z]+(([\'\-][a-zA-Z])?[a-zA-Z]*)*$",
minlength: 2,
messages:{
minlength:"Must be 2 characters."
}
}
};
}
}
现在,如果你调用getRule,它将返回一个像这样的对象
var myruleDef = getRule(rule);
$(selector).rules(myruleDef.param1, myruleDef.param2);
答案 1 :(得分:0)
您可以将规则存储在地图中:
var rules = {
fName: {
regexName: "^[a-zA-Z]+(([\'\-][a-zA-Z])?[a-zA-Z]*)*$",
minlength: 2,
messages: {
minlength: "Must be 2 characters."
}
},
lName: { // ... }
// ...
};
并将所有这些应用于:
for (var id in rules) {
$("#" + id).rules("add", rules[id]);
}
注意:break
之后您不需要return
。
注2:为了便于阅读,请包装并缩进对象文字。