vue 身份证格式校验_chen_ai_tao的博客-CSDN博客_vue 身份证校验
Vue中根据输入的身份证号识别年龄、性别_cx&lavender的博客-CSDN博客_vue中根据省份证获取年龄和性别
表单项绑定@input 事件
定义身份证校验规则
data() {
const isCnNewID = (rule, value, callback) => {
var arrExp = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];//加权因子
var arrValid = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];//校验码
if (/^\d{17}\d|x$/i.test(value)) {
var sum = 0, idx;
for (var i = 0; i < value.length - 1; i++) {
// 对前17位数字与权值乘积求和
sum += parseInt(value.substr(i, 1), 10) * arrExp[i];
}
// 计算模(固定算法)
idx = sum % 11;
// 检验第18为是否与校验码相等
if (arrValid[idx] == value.substr(17, 1).toUpperCase()) {
callback()
} else {
this.person.gender = ''
this.person.birthday = ''
callback("身份证格式有误")
}
} else {
this.person.gender = ''
this.person.birthday = ''
callback("身份证格式有误")
}
}
return {
personRules: {
//身份证校验规则
cardNo: [
{ required: true, message: "请输入身份证号", trigger: "blur" },
{ //调用定义的方法校验格式是否正确
validator: isCnNewID, trigger: "blur"
}
],
}
}
}
识别性别、出生日期
methods: {
// 身份证识别性别出生日期
inputChange() {
const reg =
/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
if (reg.test(this.person.cardNo)) {
var org_birthday = this.person.cardNo.substring(6, 14);
var org_gender = this.person.cardNo.substring(16, 17);
var sex = org_gender % 2 == 1 ? "男" : "女";
var birthday =
org_birthday.substring(0, 4) +
"-" +
org_birthday.substring(4, 6) +
"-" +
org_birthday.substring(6, 8);
var birthdays = new Date(birthday.replace(/-/g, "-"));
this.person.gender = sex;
this.person.birthday = birthdays;
} else {
return false;
}
},
}