Element-UI 动态设置form验证规则
问题:选择switch 改变 ruleForm.delivery 的值,动态实现校验生效
1、去除rules中需要动态校验的字段规则
// 去除前
rules: {
name: [
{ required: true,message: "请输入名称",trigger: "blur" }
],
region: [
{ required: true, message: "请选择条件", trigger: "blur" }
]
}
// 去除后
rules: {
name: [
{ trigger: "blur" }
],
region: [
{ required: true, message: "请选择条件", trigger: "blur" }
]
}
2、在prop字段为name的form-item上,添加required属性
下面代码isHaveTo为新字段,根据下拉框选择的值来决定是为true还是false
<el-form-item label="名称" prop="name" :required="isHaveTo">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
3、计算属性,新增字段isHaveTo
下拉选择框为1是非必填,其他都是必填,包括默认
computed: {
isHaveTo: function() {
return this.ruleForm.region !== 1;
}
},
4、设置错误提示,使用自定义函数控制流程,把name字段重新加回去rules
注意是函数
data() {
// 验证名称的函数
let validateName = (rule, value, callback) => {
// 当名称为空值且为必填时,抛出错误,反之通过校验
if (this.ruleForm.name === "" && this.isHaveTo) {
callback(new Error("请输入名称"));
} else {
callback();
}
};
return {
ruleForm: {
name: "",
region: ""
},
rules: {
name: [{trigger: "blur" , validator: validateName }],
region: [
{ required: true, message: "请选择条件", trigger: "blur" }
]
}
};
},
自定义函数validator在 return 之前
vue代码:
<template>
<div>
<el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="名称" prop="name" :required="isHaveTo">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item label="条件" prop="region">
<el-select v-model="ruleForm.region" placeholder="请选择条件" style="width:100%">
<el-option label="必填" value="0"></el-option>
<el-option label="非必填" value="1"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
// 验证名称的函数
let validateName = (rule, value, callback) => {
// 当名称为空值且为必填时,抛出错误,反之通过校验
if (this.ruleForm.name === "" && this.isHaveTo) {
callback(new Error("请输入名称"));
} else {
callback();
}
};
return {
ruleForm: {
name: "",
region: ""
},
rules: {
name: [{ trigger: "blur",validator: validateName }],
region: [
{ required: true, message: "请选择条件", trigger: "blur" }
]
}
};
},
computed: {
isHaveTo: function() {
return this.ruleForm.region !== 1;
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
console.log(`已提交表单`);
} else {
console.log("error submit!!");
return false;
}
});
}
}
};
</script>