element-ui中有关联逻辑关系的表单校验

具体的UI展示如下:

https://img2.mukewang.com/5c9d8c2c0001d29008000613.jpg

数据格式为:


data: [

    { label: '顺丰', value: '' },

    { label: '韵达', value: '' },

    { label: '圆通', value: '' },

    // ...动态数据,可能还有更多

]

校验规则及显示:


必填校验;否则标红对应输入框,并在对应输入框下显示'请输入单量比例'

格式校验;比例值必须是大于0的数字类型,否则标红对应输入框,在对应的输入框下显示‘输入值必须为正数’

关联交验:各个单量比例之和必须为100,否则标红所有输入框,并在所有输入框下显示'比例之和必须为100%'

前两个没有关联逻辑的校验element-ui中有提供,但是关联关系的逻辑没什么思路,劳烦大牛有方法的提供一下具体的思路(最好能贴出代码),万分感谢!


采用一楼的方式只能校验当前项是否满足,无法将前面填写的置为合法

https://img4.mukewang.com/5c9d8c3500012a4f04080756.jpg

BIG阳
浏览 2761回答 2
2回答

翻翻过去那场雪

折腾了这么久,终于弄出来了,主要问题是:当校验条件满足时,需要重新校验所有表单的合理性&nbsp;<el-form :model="ruleForm" ref="form">&nbsp; <div v-for="(item, index) in ruleForm.proportion" :key="index">&nbsp; &nbsp; <el-form-item class="left label"&nbsp; &nbsp; &nbsp; :label="`${item.label}:`"&nbsp; &nbsp; &nbsp; :rules="rule"&nbsp; &nbsp; &nbsp; :prop="'proportion.' + index + '.value'">&nbsp; &nbsp; &nbsp; <el-input v-model.number="item.value"></el-input>%&nbsp; &nbsp; </el-form-item>&nbsp; </div></el-form>// created初始化this.rule = [&nbsp; { required: true, message: '请输入单量比例', trigger: 'blur' },&nbsp; { type: 'integer', min: 1, max: 100, message: '输入值必须介于1至100', trigger: 'blur' },&nbsp; { validator: this.checkSum, trigger: 'blur' },];// methods方法checkSum(rule, value, callback) {&nbsp; let sum = 0;&nbsp; this.items.forEach((item) => {&nbsp; &nbsp; sum += item.value;&nbsp; });&nbsp; if (sum !== 100) {&nbsp; &nbsp; this.isLegal = false;&nbsp; &nbsp; callback(new Error('比例之和必须为100%'));&nbsp; } else {&nbsp; &nbsp; this.isLegal = true;&nbsp; &nbsp; callback();&nbsp; }},// watch监控isLegal() {&nbsp; this.$refs.form.validate((validate) => {&nbsp; &nbsp; this.isLegal = validate;&nbsp; });},

一只萌萌小番薯

利用validator定义自己的验证规则,伪代码如下。&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; { 规则1... },&nbsp; &nbsp; &nbsp; &nbsp; { 规则2... },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; validator: function(rule, value, callback) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum(this.data) === 100 ? callback() : callback(new Error("比例之和必须为100%"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; trigger: 'blur'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript