设置 rules, 并制定 prop
<Form ref="topicForm" :model="topicForm" :rules="topicFormValidate" :label-width="80">
<FormItem label="名称" prop="topicName">
<Input
type="text"
v-model="topicForm.topicName"
placeholder="请输入名称"
style="width: 180px"
/>
</FormItem>
</Form>
代码校验与重置
// 校验
this.$refs.topicForm.validate(valid => {
if (valid) {
...
}
}
// 重置
this.$refs.topicForm.resetFields();
自定义校验
export default {
name: "add-topic",
data() {
const validateName = (rule, value, callback) => {
if (value) {
checkTopicName(value)
.then(() => {
callback();
})
.catch(() => {
callback(new Error("名称重复"));
});
} else {
callback();
}
};
return {
topicName: [
{required: true, message: "名称不能为空", trigger: "blur"},
{validator: validateName, trigger: "blur"},
]
}
}
}
指定长度
topicName: [
{required: true, message: "名称不能为空", trigger: "blur"},
{validator: validateName, trigger: "blur"},
{
min: 6,
max: 36,
message: '专题名称长度为 6~36 位'
}
]
指明数据类型 type
有时候,明明写了值,但是提示不能为空,比方说 select 组件就会有这个问题。
<FormItem label="模板" prop="templateId" v-show="createMode === 'create'">
<Select
v-model="topicForm.templateId"
style="width: 180px"
@on-change="onTemplateChange"
clearable
filterable
>
<Option
v-for="item in templateList"
:value="item.id"
:key="item.id"
>{{ item.name }}
</Option>
</Select>
这是因为默认校验数据类型为String,而实际用到的 value 是数字,所以需要制定 type
{required: true, type: “number”, message: “模板不能为空”, trigger: “blur”},
触发条件
有时只是用 blur 不一定能满发需求,比方说这种直接复制的,可以添加触发条件 change。或者 select 组件已经选了值,还是提示不能为空,点了提交按钮才重新校验,这也可以通过添加 change 触发器解决。
image-20190806145320917
Iview 不支持直接给 trigger 赋值数组,需要分开写:
templateId: [
{required: true, type: "number", message: "模板不能为空", trigger: "blur"},
{required: true, type: "number", message: "模板不能为空", trigger: "change"},
]
动态增加校验项
if (select.value === "copy") {
this.$delete(this.topicFormValidate, "templateId");
this.$set(this.topicFormValidate, "copyId", [
{required: true, message: "ID 不能为空", trigger: "blur"},
{required: true, message: "ID 不能为空", trigger: "change"}
]);
} else if (select.value === "create") {
this.$delete(this.topicFormValidate, "copyId");
this.$set(this.topicFormValidate, "templateId", [
{required: true, type: 'number', message: "模板不能为空", trigger: "blur"},
{required: true, type: 'number', message: "模板不能为空", trigger: "change"},
]);
}