let rule = { name: /^\S/, password: /^([A-Za-z0-9]){6,16}$/}let user = { name: 'xiaoming', password: '1234'}if(rule.name.test(user.name)){ console.log('name 通过')}else{ console.log('name 不通过') }if(rule.password.test(user.password)){ console.log('password 通过')}else{ console.log('password 不通过') }如果user属性很多的话,这样子校验正则很啰嗦。是否有更好的写法?
1 回答
动漫人物
TA贡献1815条经验 获得超10个赞
看了一下示例代码,如果说user属性key都能在rule找到对应的key的话,可以这么写:
let rule = {
name: /^\S/,
password: /^([A-Za-z0-9]){6,16}$/
}
let user = {
name: 'xiaoming',
password: '1234'
}
for(key in user){
if(rule[key]) {
if(rule[key].test(user[key])){
console.log(key+' pase');
}else{
console.log(key+' fail')
}
}
}
添加回答
举报
0/150
提交
取消