前端通常都是使用正则来校验嗷~有一次我前端放过去了结果被后台拦住了你说气不气??
我把后台的java校验身份证方法拿过来转成了js~~~~
用了正则和其它的方法来校验身份证号的真伪
先讲一下身份证大概的。。那什么。。。。咋个说?颁发的规则??
http://www.ip33.com/shenfenzheng.html
我的代码全部都参考👆这里的
上代码 👇
/**
* 身份证校验
* 返回出生日期、性别及年龄
*/
export function validateIdNumber(certNo) {
let birthday = null;
let sex = null;
let age = -1;
if (certNo.length != 15 && certNo.length != 18)
return false;
// 15位的全部或18位的前17位必须位数字
let str = certNo.length === 15 ? certNo : certNo.substring(0, 17);
let regNum = /^\d+$/;
if (!regNum.test(str))
return false;
// 18位的最后一位可以是X或x
let regLast = /[0-9Xx]/;
let numLast = certNo.substring(17, 18);
if (certNo.length === 18 && !regLast.test(numLast))
return false;
// 前两位对应的区位码
let zoneArr = [11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 50, 51, 52, 53, 54, 61, 62, 63, 64, 65, 71, 81, 82, 91];
if (zoneArr.indexOf(parseInt(certNo.substring(0, 2))) == -1)
return false;
// 校验年份、月份、日子
let year = certNo.length === 15 ? `19${certNo.substring(6, 8)}` : certNo.substring(6, 10);
let month = certNo.length === 15 ? certNo.substring(8, 10) : certNo.substring(10, 12);
let day = certNo.length === 15 ? certNo.substring(10, 12) : certNo.substring(12, 14);
let dayNum = parseInt(day);
let monthNum = parseInt(month);
let yearNum = parseInt(year);
let currentYear = new Date().getFullYear();
if (yearNum < 1900 || yearNum > currentYear)
return false;
if (monthNum > 12 || monthNum < 1)
return false;
if ((monthNum === 1 || monthNum === 3 || monthNum === 5 || monthNum === 7 || monthNum === 8 || monthNum === 10 || monthNum === 12) && dayNum > 31)
return false;
if ((monthNum === 4 || monthNum === 6 || monthNum === 9 || monthNum === 11) && dayNum > 30)
return false;
// 校验闰平年二月的天数
if (monthNum === 2) {
let leapYear = null;
// 闰年
if (yearNum % 4 === 0 && yearNum % 100 != 0)
leapYear = dayNum > 29 ? false : true;
else {// 平年
leapYear = dayNum > 28 ? false : true;
}
if (!leapYear) {
return false;
}
}
// 上面这部分的代码语法用得太恶心了。。实不相瞒我转行来的,基础太差了正在补。。爸特它虽然恶心但好用哈哈哈哈哈
birthday = `${year}-${month}-${day}`;
age = currentYear - year;
if (certNo.length === 18) {
sex = certNo.substring(16, 17) % 2 === 0 ? '女' : '男';
} else {
sex = certNo.substring(13, 14) % 2 === 0 ? '女' : '男';
}
// 校验 校验码
const powerList = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const paritybitList = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
let num = 0;
let certArr = certNo.split('').map(Number).slice(0, 17);
for (let i = 0; i < certArr.length; i++) {
num += (certArr[i] * powerList[i]);
}
if (certNo[17] != paritybitList[num % 11]) {
if (num%11 === 2) {
if(certNo[17] != 'x' && certNo[17] != 'X')
return false;
} else {
return false;
}
}
return {
birthday,
sex,
age
};
}
网友评论