el-from 内使用的数据需使用 :model 相关联的值方可正常使用,关联值为数组状态 :rules="clientFormRules" 指明了校验规则使用rules规则对象,名称自定义;prop项,指明哪些字段可能使用校验规则
<el-form id="clientForm" ref="client" :model="clientForm" :rules="clientFormRules" label-width="110px" label-position="left">
<el-card class="box-card" shadow="hover">
<el-row>
<el-col :span="8">
<el-form-item label="名称" prop="titleValue">
<el-input v-model="clientForm.titleValue" maxlength="50" :disabled="false" />
</el-form-item>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-form-item label="简介" prop="contentValue">
<el-input v-model="clientForm.contentValue" maxlength="500" type="textarea" :autosize="{ minRows: 2, maxRows: 20}" :disabled="false" />
</el-form-item>
</el-col>
</el-row>
</el-card>
</el-form>
clentFrom为 :model 相关联的数组定义在data(return{})内,其名称必须与form的:rules属性绑定的rules规则对象名一致,clientFromRules 为定义相关的规则定义在data()内
data() {
var checkTitle = (rule, value, callback) => {
if (!value) {
return callback(new Error('名称为空'))
} else {
callback()
}
}
var checkContent = (rule, value, callback) => {
if (!value) {
return callback(new Error('简介为空'))
} else {
callback()
}
}
return {
loading: false,
publish_note: false,
activeButton: '保存',
title: '新增',
table_loading: false,
maxTableHeight: '650px',
tableData: [],
selectedContent: [],
total: 0,
pageSize: 10,
currentPage: 1,
clientForm: {
titleValue: '',
contentValue: ''
},
clientFormRules: {
titleValue: [{
required: true,
validator: checkTitle,
trigger: 'blur'
}],
contentValue: [{
required: true,
validator: checkContent,
trigger: 'blur'
}]
}
}
},
rule项
rule项,即规则数组的元素,这是本文要重点探讨的项目。这里先就上述rules的各元素项解析一下:
- required:表示是否必须有值,取值为true/false,如为true,表示必须有值,如果无值,则校验不通过;如为false,则允许无值,但在有值的情况下,不影响其它规则的使用。
- message:提示消息,在校验不通过时提示此消息。
- trigger:触发方式,取值为blur/change,blue表示失去焦点,一般在input组件中使用;change为值改变,一般在选择框中使用。
- min:字符串最小长度。
- max:字符串最大长度。
validate 任一表单项被校验后触发,后跟自定规则 validator: checkContent 规则定义在data内,不论结果是否正确都要执行 callback()
var checkContent = (rule, value, callback) => {
if (!value) {
return callback(new Error('掲載強化文言を入力してください。'))
} else {
callback()
}
}
Type 内置类型(定义在prop关联的数据内,非定义类型的数据就会报错)
string
: 必须是string
.This is the default type.
number
: 必须是number
.boolean
: 必须是boolean
.method
: 必须是function
.regexp
: 必须是正则或者是在调用new RegExp
时不报错的字符串.integer
: 整数.float
: 浮点数.array
: 必须是数组,通过Array.isArray
判断.object
: 是对象且不为数组.enum
: 值必须出现在enmu
枚举值中.date
: 合法的日期,使用Date
判断url
: url.hex
: 16进制.email
: 邮箱地址.
contentValue: [{
type: "string",
required: true,
validator: checkContent,
trigger: 'blur'
}]