(编辑:jimmy 日期: 2024/12/22 浏览:2)
这里以项目的需求为例,基本的需求如下:
代码如下:(页面)
<el-col :span="8" v-if="item.qttccType === 1"> <el-col :span="14"> <el-form-item :label="item.qttccName" :prop="'list.'+ index + '.startNum'" :rules="item.qttccName === '交易金额' "> <el-input v-model.number="item.qttcStartNum" style="width: 100%;" @change="handleMinChange(index)"></el-input> </el-form-item> </el-col> <el-col :span="10"> <el-form-item label="~" label-width="10px" :prop="'list.'+ index + '.qttcEndNum'" :rules="item.qttccName === '交易金额' "> <el-input v-model.number="item.qttcEndNum" style="width: 60%;" @change="handleMaxChange(index)"></el-input> </el-form-item> </el-col> </el-col>
根据上面的思路,单个表单的校验属于公共校验方法,关联校验需要分别校验(因为对比对象不同,且提示语不同),由此在自定义校验中有了如下定义:
公共校验方法:正整数校验、区间校验
validateCom(rule, value, callback) { const MIN_NUMBER = 1 const one = Number(value) if (Number.isInteger(one)) { if (one < MIN_NUMBER) { return callback(new Error('输入值必须大于0')) } else if (one.length > 50) { callback(new Error('最大长度为50位')) } return callback() } return callback(new Error('请输入数字值')) }
关联校验:
startMoneyRule(index) { const validateMin = (rule, value, callback) => { const one = Number(value) const max = Number(this.form.list[index].qttcEndNum) if (!max || one < max) { return callback() } return callback(new Error('输入值不得大于最大阈值')) } const R = [] R.push({ required: false, message: '请填写交易金额最小值', trigger: 'blur' }, { validator: this.validateCom, trigger: 'blur' }, { validator: validateMin, trigger: 'blur' }) return R }, endMoneyRule(index) { const validateMax = (rule, value, callback) => { const one = Number(value) const min = Number(this.form.list[index].qttcStartNum) if (!min || one > min) { return callback() } return callback(new Error('输入值不得小于最小阈值')) } const R = [] R.push({ required: false, message: '请填写交易金额最大值', trigger: 'blur' }, { validator: this.validateCom, trigger: 'blur' }, { validator: validateMax, trigger: 'blur' }) return R }
很显然,左侧值是小于右侧值的,但是校验提示仍然报错。究其原因,还是关联校验的问题。既然是关联交验,改变其中一个时应该会重新校验两个。很简单,在input改变时,重新校验表单不就OK了吗
handleMinChange(index) { this.$refs.form.validateField('list.' + index + '.qttcEndNum') }, handleMaxChange(index) { this.$refs.form.validateField('list.' + index + '.qttcStartNum') }
大功告成,忘说了。我的表单是动态从后台获取的,所以校验rules是动态加的!!!