1.校验15、18位身份证
const regCart = /(^[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]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
缺点:未校验2月份的天数不超过28
2.校验手机号码
const regExp = /^1(3|4|5|7|8)\d{9}$/;
3.根据身份证计算出生日期、年龄、性别
calculateCard(str) {
const ret = {
birthday: null,
age: null,
gender: null,
};
const len = str.length;
if (len === 15 || len === 18) {
// 计算出生日期 - birthday
if (len === 18) {
ret.birthday = `${str.substr(6, 4)}-${str.substr(10, 2)}-${str.substr(12, 2)}`;
}
if (len === 15) {
ret.birthday = `19${str.substr(6, 2)}-${str.substr(8, 2)}-${str.substr(10, 2)}`;
}
// 计算年龄 - age
const ageVal = new Date(ret.birthday);
const nowDateTime = new Date();
ret.age = nowDateTime.getFullYear() - ageVal.getFullYear();
// 月、天的差异
if (nowDateTime.getMonth() < ageVal.getMonth() ||
(nowDateTime.getMonth() === ageVal.getMonth() && nowDateTime.getDate() < ageVal.getDate())) {
ret.age -= 1;
}
// 计算性别 - gender
ret.gender = (parseInt(str.substr(16, 1), 10) % 2 === 1) ? '男' : '女';
}
return ret;
},