#身份证 由于项目有要求对身份证进行严格模式校验,针对市场上身份证对于格式地区生日等进行处理
function validateIdentityId(identityId) {
// 长度和格式校验
if (!/^\d{15}(?:\d{2}[0-9Xx])?$/.test(identityId)) {
return { valid: false, message: "身份证号长度或格式错误" };
}
// 地区校验
const areas = {
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: "国外",
};
const areaCode = identityId.substr(0, 2);
if (!areas.hasOwnProperty(areaCode)) {
return { valid: false, message: "身份证地区非法" };
}
// 出生日期校验
const year = parseInt(identityId.substr(6, 4), 10);
const month = parseInt(identityId.substr(10, 2), 10);
const day = parseInt(identityId.substr(12, 2), 10);
if (month < 1 || month > 12) {
return { valid: false, message: "身份证上的月份非法" };
}
const isLeapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
const maxDaysInMonth = [31, (isLeapYear && month === 2) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
if (day < 1 || day > maxDaysInMonth) {
return { valid: false, message: "身份证上的日期非法" };
}
// 专门针对18位身份证的校验码验证
if (identityId.length === 18) {
const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
let sum = 0;
for (let i = 0; i < identityId.length - 1; i++) {
sum += parseInt(identityId[i], 10) * weights[i];
}
const expectedCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
const lastCharIndex = sum % 11;
const lastChar = identityId[identityId.length - 1].toUpperCase();
const expectedLastChar = expectedCodes[lastCharIndex];
if (lastChar !== expectedLastChar) {
return { valid: false, message: "身份证号校验码错误" };
}
}
return { valid: true, message: "身份证号验证通过" };
}