面对复杂表单,我们可以尝试使用async-validator工具来进行校验
比如画圈部分分别添加不同的校验
1、下包
yarn add async-validator
2、引入依赖
import Validator from 'async-validator';
3、配置规则
const rules = {
schemeName: { type: 'string',required: true ,message:'方案名称不能为空'},
insName: { type: 'string',required: true , message: '险种名称不能为空'}
}
4、实例化校验规则工具
const validator = new Validator(rules)
5、开始校验
validator.validate({
...values
}, (errors, fields) => {
if (errors) {
// 抛出第一个异常
return console.log(errors[0].message)
} else {
console.log(12132)
}
})
完整代码
//1、引入依赖
import Validator from 'async-validator';
// 2、配置规则
const rules = {
schemeName: { type: 'string',required: true ,message:'方案名称不能为空'},
insName: { type: 'string',required: true , message: '险种名称不能为空'}
}
// 3、实例化校验规则工具
const validator = new Validator(rules)
// 4、配置要进行校验的表单key 、 value
const values = {
schemeName:this.ruleForm.insName,
insName:this.ruleForm.schemeName
}
// 5、开始校验
validator.validate({
...values
}, (errors, fields) => {
if (errors) {
// 抛出第一个异常
return console.log(errors[0].message)
} else {
console.log(12132)
}
})