基础表单校验的步骤
1.定义校验规则
rules:{
name: [
{ required: true, message: '部门名称不能为空', trigger: 'blur'},
{ min: 1, max: 50, message: '部门名称要求1-50个字符', trigger:'blur'},
{ validator: validName, trigger: 'blur'}
],
code: [
{ required: true, message: '部门编码不能为空', trigger: 'blur'},
{ min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur'},
{ validator: validCode, trigger: 'blur'}
],
manager: [
{ required: true, message: '部门负责人不能为空', trigger: 'blur'}
],
introduce: [
{ required: true, message: '部门介绍不能为空', trigger:'blur'},
{ min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur'}
]
}
2.配置模板,应用规则
- 给表单设置
rules
属性传入验证规则 - 给表单设置
model
属性传入表单数据 - 表单中ref属性的作用类似于id,可以方便的找到对应的浏览器的dom对象
- 给表单中的元素(Form-Item )设置
prop
属性,其值为设置为需校验的字段名
<el-form :rules="rules" :model="form" ref="deptForm" label-width="120px">
<el-form-item label="部门名称" prop="name">
<el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
</el-form-item>
</el-form>
3.手动兜底验证