记录一个el-select复选框表单校验例子
1、一打开页面就会触发校验
解决方案:设置初始值为空数组
2、选中下拉数据,不会再次触发校验,导致提示文字一直存在
解决这个问题,首先先看看v-model 、prop属性、rules校验是否正确,这里注意el-select的rules校验的trigger应该是change。
如果以上都没问题,那么还有一个原因就是:嵌套太深,导致form检测不到ruleForm的变化
解决方案:
javascript
// 我这里用的是
vulTypeChange() {
this.form = { ...this.form }
},
3、完没解决思路
1)添加form表单:rule方式验证
html
<el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-bottom: 20px">
<el-row>
<el-col :span="12">
<el-form-item label="接收人" prop="receivers">
<el-select v-model="form.receivers" placeholder="请选择接收人" filterable multiple clearable style="width: 100%" :disabled="this.disabled"
>
<el-option v-for="item in users" :key="item.userName" :label="item.nickName" :value="item.userName" />
</el-select>
</el-form-item>
</el-col>
</el-row>
</el-form>
javascript
rules: {
receivers: [
{ required: true, validator: picValidator, trigger: 'change' },
]
},
注意rule中验证方式应该是"change"
2)给下拉框添加change函数
html
<el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-bottom: 20px">
<el-row>
<el-col :span="12">
<el-form-item label="接收人" prop="receivers">
<el-select v-model="form.receivers" placeholder="请选择接收人" filterable multiple clearable style="width: 100%" :disabled="this.disabled"
@change='vulTypeChange'>
<el-option v-for="item in users" :key="item.userName" :label="item.nickName" :value="item.userName" />
</el-select>
</el-form-item>
</el-col>
</el-row>
</el-form>
@change='vulTypeChange'
javascript
vulTypeChange() {
this.form = { ...this.form }
},
3)自定义校验方法
javascript
data() {
// 自定义验证规则
var picValidator = (rule, value, callback) => {
if (!this.form.receivers.length) {
// 一定要写 callBack() 验证完成时调用的回调函数 https://github.com/yiminghe/async-validator
callback(new Error('请至少选择一个接收人'))
} else {
callback()
}
}
return {
。。。。
至此,完美解决el-select复选框表单校验