validateRules: { certno: [ { required: true, message: '证件号码不能为空' }, { validator: (rule, value) => { return new Promise((resolve, reject) => { const result = verify(value); if (result.status === 0) { resolve(); } else { reject(new Error(result.msg)); } }); }, message: '请输入正确的身份证号码' } ], name: [ { required: true, message: '姓名不可为空' } ], empName: [ { required: true, message: '单位名称不可为空' } ], empCode: [ { required: true, message: '统一信用代码不能为空' }, { validator: (rule, value) => { return new Promise((resolve, reject) => { if (/^[A-Z0-9]{18}$/.test(value)) { resolve(); } else { reject(new Error('请输入正确的统一信用代码')); } }); } } ], reason: [ { required: true, message: '失信原因不能为空' } ] } 优化下这段代码
时间: 2024-02-10 19:20:07 浏览: 103
这段代码可以进行以下优化:
1. 使用正则表达式验证证件号码,不需要自己写验证函数。
2. 将验证函数提取为公共函数,避免重复代码。
3. 将验证规则抽离到单独的变量中,方便维护和修改。
4. 将多个验证规则合并为一条,减少代码量。
下面是优化后的代码:
```
const rules = {
certno: [
{ required: true, message: '证件号码不能为空' },
{ pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码' }
],
name: [
{ required: true, message: '姓名不可为空' }
],
empName: [
{ required: true, message: '单位名称不可为空' }
],
empCode: [
{ required: true, message: '统一信用代码不能为空' },
{ pattern: /^[A-Z0-9]{18}$/, message: '请输入正确的统一信用代码' }
],
reason: [
{ required: true, message: '失信原因不能为空' }
]
};
const validateRules = {};
for (let key in rules) {
validateRules[key] = rules[key].map(rule => {
if (rule.validator) {
return {
validator: (rule, value) => {
return new Promise((resolve, reject) => {
const result = rule.validator(value);
if (result.status === 0) {
resolve();
} else {
reject(new Error(result.msg));
}
});
},
message: rule.message
};
} else {
return rule;
}
});
}
```
阅读全文