本文介绍了两种特殊表单的校验方式。
1. 对象里包含数组
2. 对象里包含对象
首先看第一种,对象里包含数组,表单通过v-for
生成
示例代码如下:
<el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
>
<el-form-item label="年龄" prop="age">
<el-input v-model.number="ruleForm.age"></el-input>
</el-form-item>
<!-- start---看这里!---start -->
<div v-for="(item,index) in ruleForm.citiesList" :key="index">
<el-form-item
:label="index==0?'去过的城市:':''"
:prop="`citiesList[${index}].name`"
:rules="citiesList.name"
required
>
<el-input type="text" v-model="item.name"></el-input>
<el-button type="text" @click="addCity()">新增</el-button>
</el-form-item>
<!-- end---看这里!---end-->
</div>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
var checkAge = (rule, value, callback, params) => {
// params为当前表单key值和value拼接成的字符串,如 name[1]:ccc,可以通过截取params获取当前索引
let key = Object.keys(params)[0]
let index = +key.replace(/\D+/g, '')
// 在此编写具体校验逻辑
if (!value) {
return callback(new Error('年龄不能为空'));
}
};
return {
ruleForm: {
age: '',
citiesList: [
name: ''
]
},
rules: {
age: [
{ validator: checkAge, trigger: 'blur' }
]
},
// 注意此处
citiesList: {
name: [
{required:true,message: '请输入城市名称', trigger: ['change', 'blur']}
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
}
addCity() {
this.ruleForm.citiesList.push([ name: ''])
}
}
}
</script>
对象中包含对象
第二种情况示例代码如下:
<el-form :model="form" :rules="rules">
<el-form-item label="收件人邮箱:" prop="mailVo.receiver" required>
<el-input type="text" v-model="form.mailVo.receiver" />
</el-form-item>
</el-form>
data () {
return {
form: {
mailVo: { receiver: '' }
},
rules: {
receiver: [{ required: true, message: '请输入收件人邮箱', trigger: ['blur', 'change'] }]
}
}
表单绑定了 form.mailVo.receiver
,如果像上面代码中rules
那样写,是起不了校验作用的。
只需改成:
rules: {
'mailVo.receiver': [{ required: true, message: '请输入收件人邮箱', trigger: ['blur', 'change'] }]
}
一定要记得加引号~