如何为对象应用一组验证规则?这些是我的验证规则。
var rules = {
p1: {
"required" : true,
"pgName" : 'string',
"type": "template2"
},
p2 : {
"required" : true,
"pgName" : 'string',
"type": "template2",
"maxLength": 30
}
}
这些是我需要对其进行验证的对象。我需要获取验证规则对象。
var obj = {
p1: {
"pgName" : 'page1',
},
p2 : {
"pgName" : 'page2',
"type": "template"
},
p3 : {
"pgName" : 'page3',
"type": "template2"
}
}
我试图遍历对象并使用相同的键匹配规则
for (var property in obj){
for(var key in rules){
if (typeof obj[property] !== rules[key]){
console.log(property + ' does not meet the rules');
}
};
};
答案 0 :(得分:0)
如果您只是希望将规则及其对象放在一起,则不需要两个for循环。这可以通过一个for循环和一个条件语句来完成。这样更具可读性。
var rules={p1:{required:!0,name:"string"},p2:{required:!0,name:"string",maxLength:30}},obj={p1:{pgName:"page1"},p2:{pgName:"page2",type:"template"},p3:{pgName:"page3",type:"template2"}};
for(let key in rules) {
if(key in obj) {
//do something
}
}
证明两个对象均可以访问:
var rules={p1:{required:!0,name:"string"},p2:{required:!0,name:"string",maxLength:30}},obj={p1:{pgName:"page1"},p2:{pgName:"page2",type:"template"},p3:{pgName:"page3",type:"template2"}};
for(let key in rules) {
if(key in obj) {
//do something
let combined = Object.assign(rules[key], obj[key]);
console.log( combined );
}
}
此外,如果您要验证必填字段,则可以轻松修改以上代码的简单扩展名,以在规则中需要但字段不在对象内时抛出错误。
var rules={p1:{required:!0,name:"string"},p2:{required:!0,name:"string",maxLength:30}, p5: {required: true}},
obj={p1:{pgName:"page1"},p2:{pgName:"page2",type:"template"},p3:{pgName:"page3",type:"template2"}};
for(let key in rules) {
if(key in obj) {
//do something
}
else {
if(rules[key]["required"]) throw Error("Required Object Not Available");
}
}
从这一点上很容易弄清其他限制。