1.首先放出结论,自定义验证规则必须降所有的可能全部都return callback出去,不然不会走validate
错误示范
// template
<el-form
ref="ruleFormRef"
:model="ruleForm"
:rules="rules"
label-width="120px"
class="demo-ruleForm"
>
<el-form-item label="名字" prop="name">
<el-input v-model="ruleForm.name" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">验证</el-button>
</el-form-item>
</el-form>
//script
import { reactive, ref } from "vue";
const ruleForm = reactive({
name: "",
});
const nameChange = (rule, value, callback) => {
if (!value) {
return callback(new Error("请填写名字"));
}
};
const rules = {
name: [
{
validator: nameChange,
trigger: "blur",
},
],
};
const submitForm = async () => {
ruleFormRef.value.validate((valid) => {
if (valid) {
alert("ok");
} else {
alert("no");
}
});
};
2.效果如下
3.可以看到含有return callback的未填写情况是触发了ruleFormRef.value.validate,可以获取到valid的问题,但是填写了之后是不会走valid的,
4.将规则修改,使得填写之后的表单验证也有对应的return callback
const nameChange = (rule, value, callback) => {
if (!value) {
return callback(new Error("请填写名字"));
} else {
return callback();
}
};