表单验证器之动态表格验证
![](https://img2022.cnblogs.com/blog/893672/202208/893672-20220802102918076-1670141920.png)
<el-form :model="fromData" ref="fromData" label-position="left" label-width="135px" :rules="rules" > <el-form-item class="jfInp" label="得分" :required="true"> <div class="form-val"> <el-table :data="fromData.staffList" size="mini" style="width: 100%" > <el-table-column label="得分" key="4" prop="evalustionScore" align="left" > <template slot-scope="scope"> <div class="ru-table-cont"> <el-form-item v-if="type != 'exam'" :prop=" 'staffList.' + scope.$index + '.evalustionScore' " :rules="fromaDataRules.evalustionScore" > <el-input maxlength="6" v-model="scope.row.evalustionScore" @blur="changeEvalustionScore()" placeholder="请输入得分" ></el-input> </el-form-item> <span v-else> {{ scope.row.evalustionScore }} </span> </div> </template> </el-table-column> </el-table> </el-form-item> </el-form>
注:
el-form-item里面的:required="true"的作用是 这行验证标题前面会带*这种必填验证,但是验证器不会走这验证,
剩下需要注意的是表格里面的:prop以及:rules
data() { const isNumber = (rule, value, callback) => { let dl = rule.field.split('.')[1] let dd = this.fromData.staffList[dl] if (!value) { return new Error('请输入得分') } else { const reg = /^[0-9]*([.][0-9]+)?$/ const isID = reg.test(value) if (!isID) { callback(new Error('请输入正确的分数')) } else { if (parseFloat(value) > dd.score) { callback(new Error('得分不能大于分值')) } else { callback() } } } } return { fromData: { staffList: [] }, fromaDataRules: { evalustionScore: [ { required: true, message: '请输入得分', trigger: 'blur' }, { validator: isNumber, trigger: 'blur' } ] }, }
注:
这里需要注意的是dl变量可以取到这一行对应的索引是在
:prop="
'staffList.' +
scope.$index +
'.evalustionScore'
"
里面的scope.$index建立的,dd可以取到当前验证表单这一行的对象,然后后续就可以去写对应的验证逻辑了