el-form表单验证深度问题
首先看一下表单验证的方法
<el-form :rules="rules" :model="formData" res="form">
<el-form-item prop="name">
<el-input v-model="formData.name"></el-input>
</el-form-item>
</el-form>
script
data(){
return{
formData:{
name:''
},
rules:{
name:{required: true, message: '请输入活动名称', trigger: 'blur'}
}
}
}
rules:表单验证的地方;
model:验证的值;
res:兜底验证使用,具体请看官网
这是正常的表单验证
有的时候我们的验证不止只在formData里面,它里面还有对象。。。
<el-form :rules="rules" :model="formData" res="form">
<el-form-item prop="name">
<el-input v-model="formData.one.name"></el-input>
</el-form-item>
</el-form>
script
data(){
return{
formData:{
one:{
name:''
}
},
rules:{
name:{required: true, message: '请输入活动名称', trigger: 'blur'}
}
}
}
这样肯定是验证不到的,因为el-form 标签上面的:model只对formData中的值校验(大白话就是看看formData中的name值存不存在)
可以再 el-form-item prop="name"上面加层级例如:
<el-form :rules="rules" :model="formData" res="form">
<el-form-item prop="one.name">
<el-input v-model="formData.one.name"></el-input>
</el-form-item>
</el-form>
script
data(){
return{
formData:{
one:{
name:''
}
},
rules:{
one:{
name:{required: true, message: '请输入活动名称', trigger: 'blur'}
}
}
}
}
这样name就可以校验了 -。- 我
v-for循环后表单验证
<el-form :rules="rules" :model="formData" res="form">
<el-form-item v-for="(item,index) in formData.formlist" :key="index" >
<el-input v-model="item.value"></el-input>
</el-form-item>
</el-form>
script
data(){
return{
formData:{
formlist:[{id:1,value:"name"},{id:1,value:"name"}.{id:1,value:"name"}]
},
rules:{
name:{required: true, message: '请输入活动名称', trigger: 'blur'}
}
}
}
表单验证怎么办呢,你定义prop肯定是验证不到的,
//首先动态绑定prop => :prop
//然后再去绑定一个 :rules
//在rules中定一个formlist和yanzheng两个验证
<el-form :rules="rules" :model="formData" res="form" >
<el-form-item v-for="(item,index) in formData.formlist" :key="index" :prop=`formlist[${index}].value` :rules="rules.yanzheng">
<el-input v-model="item.value"></el-input>
</el-form-item>
</el-form>
script
data(){
return{
formData:{
formlist:[{id:1,value:"name"},{id:1,value:"name"}.{id:1,value:"name"}]
},
rules:{
formlist:{
value:{required: true, message: '请输入活动名称', trigger: 'blur'}
}
yanzheng:{required: true, message: '请输入活动名称', trigger: 'blur'}
}
}
}
纯手写,不知道有没有错,大概思路就是这样