之前的form表的数组的校验只能单纯的处理单一的必填校验,如果有多个校验条件就不好处理了,所以换了一种写法:
上一篇form表单校验的地址::https://blog.csdn.net/qq_42323925/article/details/109613569#comments_16650949
<template>
<div class="hello">
<el-form ref="form" :model="form" :rules="rules">
<!-- 对form中的数组进行校验 -->
<div v-for="(item, index) in form.list" :key="index">
<el-form-item
label="姓名"
:prop="`list[${index}].name`"
:rules="rules.name"
>
<el-input v-model="item.name" />
</el-form-item>
<el-form-item
label="年龄"
:prop="`list[${index}].age`"
:rules="rules.age"
>
<el-input v-model="item.age" />
</el-form-item>
</div>
<el-button type="primary" @click="submitHandle"> 保 存 </el-button>
</el-form>
</div>
</template>
<script>
export default {
name: "test",
data() {
var validateAge = = (rule, value, callback) => {
//拿到对应数组中的下标
const index = Number(rule.field.replace(/[^\d]/g, ' '));
//判断条件
if ( Number(value) < 30)')) return callback();
callback(new Error('年龄不能大于30岁'));
this.form.list[index].age = ''
};
return {
form: {
list: [
{
name: "",
age: "",
},
{
name: "",
age: "",
},
],
},
rules: {
name:{ required: true, message: '请输入姓名', trigger: 'blur' },
age:[
{ required: true, message: '请输入年龄', trigger: 'blur' },
{ validator: validateAge, trigger: 'blur' }
]
},
};
},
methods: {
submitHandle() {
this.$refs["form"].validate((val) => {
if (val) {
console.log("校验成功");
} else {
console.log("校验失败");
}
});
}
},
};