第一步写好表单,并在表单中绑定校验表:rules=“rule”
<el-form class="apply-form first-form" :model="formData" :rules="rule" ref="form">
<el-form-item label="姓名" prop="visitorName">
<el-input v-model="formData.visitorName" placeholder="请输入姓名" clearable></el-input>
</el-form-item>
<el-form-item label="身份证号" prop="cardCode">
<el-input v-model="formData.cardCode" :maxlength="18" placeholder="请输入身份证号" clearable></el-input>
</el-form-item>
</el-form>
第二步在data()中填写表单校验规则,对应的校验字段要在prop中填写
如prop=“visitorName”,然后在rule{}中写上验证规则
具体校验参数规格参考https://github.com/yiminghe/async-validator
data() {
return {
formData: {
visitorName: '',
cardType: 1,
cardCode: ''
},
rule: {
visitorName: [
{ required: true, message: '请输入姓名', trigger: 'blur' },
{ min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
{
required: true,
pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
message: '姓名不支持特殊字符',
trigger: 'blur'
}
],
cardCode: [
{ required: true, message: '请输入身份证号', trigger: 'blur' },
{ min: 15, max: 18, message: '请如实填写18位号码,以供学校保卫科核对', trigger: 'blur' },
{
required: true,
pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
message: '请输入正确的身份证号码',
trigger: 'blur'
}
]
}
}
}
第三步可自定义校验规则,将校验规则写在data()中
data() {
let reg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{6,12}$/
var validateNewPwd = (rule, value, callback) => {
if (!reg.test(value)) {
callback(new Error('密码应是6-12位数字、字母或字符!'))
} else if (this.form.oldPasswd === value) {
callback(new Error('新密码与旧密码不可一致!'))
} else {
callback()
}
}
var validateComfirmPwd = (rule, value, callback) => {
if (!reg.test(value)) {
callback(new Error('密码应是6-12位数字、字母或字符!'))
} else if (this.form.newPasswd !== value) {
callback(new Error('确认密码与新密码不一致!'))
} else {
callback()
}
}
return {
form: {
newPasswd: '',
comfirmPwd: ''
},
rules: {
newPasswd: [
{ required: true, message: '请输入新密码', trigger: 'blur' },
{ validator: validateNewPwd, trigger: 'blur' }
],
comfirmPwd: [
{ required: true, message: '请输入确认密码', trigger: 'blur' },
{ validator: validateComfirmPwd, trigger: 'blur' }
]
}
}
}