前言
element的表单验证,实际项目中有部分表单数据是固定的,验证方式参考官网。也有很大一部分表单数据的label是从后台取得数据,在这种情况下验证方式就不同,也是此文所述。
后台数据常规验证(label,prop确定)
官网表单校验部分 http://element-cn.eleme.io/#/zh-CN/component/form
一、后台数据,label prop不确定,index确定——只校验非空
注意点:
:prop="'domains.' + index + '.value'"
----:prop="'循环的数组名称.' + index + '.循环的数据key值'"
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
<el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'域名' + index" :key="domain.key"
:prop="'domains.' + index + '.value'" :rules="{
required: true, message: '所选项不能为空', trigger: 'blur'
}">
</el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
</el-form>
<script>
export default {
data() {
return {
dynamicValidateForm: {
domains: [{
value: '1'
}, {
value: '2'
}],
}
};
},
methods: {
// 提交
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
}
}
}
</script>
二、后台数据,label prop不确定,index确定——多个校验规则
方法一:相同的校验规则,在el-form
整体加rules
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic" :rules="rules">
<el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :label="'域名' + index" :key="domain.key"
:prop="'domains.' + index + '.value'"