前提:表单校验:model,:prop,v-model都是正确书写,input,select,类型为date的时间选择框表单校验都能正常触发。
问题描述:
在项目中需要在表单中多次使用daterange类型的时间选择组件,但是在提交表单数据的时候,时间组件内容为空并没有触发校验规则。
提交按钮不能正常校验代码:
<el-form-item
v-for="item in surfaceContamination"
:label="item.label"
:prop="item.prop"
>
<el-date-picker
v-model="ruleForm[item.prop]"
:type="item?.dataType"
placeholder="选择时间"
range-separator="至"
start-placeholder="开始时间"
end-placeholder="结束时间"
v-if="item.type == 'time'"
:disabled="item.disabled"
:value-format="item.valueFormat"
time-format="mm:ss"
:style="
item?.dataType == 'daterange'
? 'max-width: 300px'
: 'max-width: 100%'
"
:disabled-date="item?.disabledDate"
/>
</el-form-item>
//验证规则 rules截取
radio_monitorTime: [
{
required: type == "detials" ? false : true,
message: "内容不能为空!",
trigger: ["change", "blur"],
},
],
触发:只有当点击组件内部清空,确定按钮或者清空图标的时候才能触发表单验证。其他方式都不能触发表单验证。
解决问题:
查阅element-plus文档Form 表单 | Element Plus
查阅rules写法:GitHub - yiminghe/async-validator: validate form asynchronous
1.设置需要校验数据的类型,因为daterange类型时间返回值是数组因此校验规则里面添加了type:array进行限制。
2.校验失败写法中使用默认的校验方式,此处需要针对数组自定义校验函数。
radio_monitorTime: [
{
type: 'array',
required: type == "detials" ? false : true,
message: "内容不能为空!",
trigger: ["change", "blur"],
validator: validatePass2,
},
],
const validatePass2 = (rule: any, value: any, callback: any) => {
if (!value[0] || !value[1]) {
callback(new Error("Please input the password again"));
} else {
callback();
}
};
分别去校验数组中不同值是否符合要求。做完这些再次点击提交按钮就可以按照我们自定义规则触发表单校验。