Element UI 使用自定义表单校验规则之后无法提交
使用自定义表单验证规则
js代码
cerNo: [
{required: true, message: "证件号不能为空", trigger: "blur"},
{validator: this.validID, trigger: ["blur"]}
],
规则定义代码
/** 验证身份证并且计算性别和出生日期*/
validID(rule, value, callback) {
// 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
if (reg.test(this.form.cerNo) && this.form.cerType == 1) {
this.go(this.form.cerNo.length);
} else if (!reg.test(this.form.cerNo) && this.form.cerType == 1) {
this.form.sex = null;
callback(new Error('身份证号码或格式不正确'));
} else {
this.requiredFlag = false; //不是身份证出生无法判断年龄
this.form.birthday = undefined;
}
//这里无论是否验证成功都需要调用callback
callback();
},
go(val) {
let iden = this.form.cerNo;
let sex1 = null;
let birth = null;
let myDate = new Date();
let month = myDate.getMonth() + 1;
let day = myDate.getDate();
let age = 0;
if (val === 18) {
age = myDate.getFullYear() - iden.substring(6, 10) - 1;
sex1 = iden.substring(16, 17);
birth = iden.substring(6, 10) + "-" + iden.substring(10, 12) + "-" + iden.substring(12, 14);
if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;
}
if (val === 15) {
age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
sex1 = iden.substring(13, 14);
birth = "19" + iden.substring(6, 8) + "-" + iden.substring(8, 10) + "-" + iden.substring(10, 12);
if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
}
if (sex1 % 2 === 0) {
sex1 = 1;
} else {
sex1 = 0;
}
this.form.sex = sex1;
this.form.birthday = birth;
let birth1 = (parseInt(iden.substring(6, 10)) + 18) + "-" + iden.substring(10, 12) + "-" + iden.substring(12, 14);
let ageBirth = new Date(birth1);
//判断当前时间与成年时间大小
if (myDate - ageBirth < 0) {
this.requiredFlag = true;
} else {
this.requiredFlag = false;
}
},
调用后台代码
/** 提交按钮 */
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
if (this.form.recordId != null) {
updateInfo(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess("修改成功");
this.open = false;
this.getList();
}
});
} else {
addInfo(this.form).then(response => {
if (response.code === 200) {
this.msgSuccess("新增成功");
this.open = false;
this.getList();
}
});
}
}
});
},
当你没有些返回callback() 回调时,你会发现你的程序既不报错,也不执行到后台;解决办法是在自定义验证方法后面调用callback() 就可以了
这样问题就轻松解决啦!!!