这不是一个简单的18位身份证正则表达式,这是包含计算规则的身份证号码验证代码。
可以直接使用,返回的是 true 或 false
/**
* 校验身份证号码有效性
* @param cardNo 身份证号码
* @param b (可选)出生日期,格式为:YYYY-MM-DD
* @param g (可选)性别,1为男,2为女
*/
function _validIdCard(cardNo, b, g) {
let date, Ai, birthday, gender;
const verify = "10X98765432";
const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','*','','','','','','','陕西','甘肃','青海','宁夏','*','','','','','','*','','','','','','','','','','香港','澳门','','','','','','','','','国外'];
let re = cardNo.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})((\d{3})[X\d])))$/i);
if(re == null) return false;
if(re[1] >= area.length || area[re[1]] == "") return false;
if(re[2].length == 12) {
Ai = cardNo.substr(0, 17);
birthday = [re[9], re[10], re[11]].join("-");
gender = re[13];
} else {
Ai = cardNo.substr(0, 6) + "19" + cardNo.substr(6);
birthday = ["19" + re[4], re[5], re[6]].join("-");
gender = re[7];
}
if(g && g != "" && (gender % 2 != g % 2)) return false;
if(b && b != "" && b != birthday) return false;
re = birthday.match(/^((19|20)\d{2})[-](\d{2})[-](\d{2})$/);
let year = re[1];
let month = re[3] * 1 - 1;
let day = re[4];
date = new Date(year, month, day);
if(typeof date != "object" || date.getFullYear() != year || date.getMonth() != month || date.getDate() != day) return false;
let sum = 0;
for(let i = 0; i <= 16; i++) {
sum += Ai.charAt(i) * Wi[i];
}
Ai += verify.charAt(sum%11);
return (cardNo.length == 15 || cardNo.length == 18 && cardNo == Ai);
};