class IDCardValidator {
static validate(id) {
// 格式检查
if (!/^\d{17}[\dXx]$/.test(id)) {
return { valid: false, message: '身份证号码格式错误' };
}
// 校验位计算
const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const checkDigits = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
let sum = 0;
for (let i = 0; i < 17; i++) {
sum += parseInt(id[i]) * weights[i];
}
const checkDigit = checkDigits[sum % 11];
const actualCheckDigit = id[17].toUpperCase();
if (checkDigit !== actualCheckDigit) {
return { valid: false, message: '身份证号码校验位错误' };
}
return { valid: true, message: '身份证号码有效' };
}
static getInfo(id) {
if (!this.validate(id).valid) return null;
const birth = id.substring(6, 14);
const year = birth.substring(0, 4);
const month = birth.substring(4, 6);
const day = birth.substring(6, 8);
const gender = parseInt(id.substring(16, 17)) % 2 === 0 ? '女' : '男';
return {
birth: `${year}-${month}-${day}`,
gender: gender,
age: new Date().getFullYear() - parseInt(year)
};
}
}