如图:实现表单输入密码和确认密码的时候进行表单校验。
实现方式:
1.在代码的data里面定义,函数验证的方法。如图所示,代码如下
【代码】如下:
const validatePassword = (rule, value, callback) => {
if (value === '') {
callback(new Error('请输入密码'));
} else {
let yz = 0;
this.passwordPercent = 0;
//6-20位包含字符、数字和特殊字符
if (this.form1.newPassword.length < 11) {
callback(new Error("长度在 11 到 20 个字符"));
}
if (this.form1.newPassword.match(/([a-z])+/)) {
yz++;
}
if (this.form1.newPassword.match(/([0-9])+/)) {
yz++;
}
if (this.form1.newPassword.match(/([A-Z])+/)) {
yz++;
}
if (this.form1.newPassword.match(/([\W_])+/)) {
yz++;
}
if (yz < 2) {
callback(new Error("密码必须是大小写字母、数字、特殊符号两种及以上组成"));
}
switch (yz) {
case 0: this.passwordPercent = 0; callback();
case 1: this.passwordPercent = 25; callback();
case 2: this.passwordPercent = 50; callback();
case 3: this.passwordPercent = 75; callback();
case 4: this.passwordPercent = 100; callback();
}
}
};
const equalToPassword = (rule, value, callback) => {
if (this.form1.newPassword !== value) {
callback(new Error("两次输入的密码不一致"));
} else {
callback();
}
};
2.设置表单校验的rule。 rule在return函数里面。名称可以自己定义。作为变量使用。
rules1: {
selectApps: [{ required: true, message: "请选择应用系统", trigger: "blur" }],
newPassword: [
{ required: true, message: "新密码不能为空", trigger: "blur" },
{ min: 8, max: 20, validator: validatePassword, trigger: "blur" }
],
confirmPassword: [
{ required: true, message: "确认密码不能为空", trigger: "blur" },
{ required: true, validator: equalToPassword, trigger: "blur" }
]
},
3.给表单添加rule。 则表单输入会按照规则进行校验。:rules="rules1"
rules1就是步骤二定义的规则
<el-form ref="form1" :model="form1" :rules="rules1" label-width="100px" v-if="radio == 1">
</el-form>