身份证号码的正确性校验是确保数据准确性和安全性的重要步骤。以下是关于身份证号码校验的基础概念、优势、类型、应用场景以及常见问题及解决方法。
身份证号码是中国公民的唯一标识,由18位数字组成,结构如下:
原因:输入的身份证号码长度不对或包含非法字符。 解决方法:
function isValidFormat(id) {
const regex = /^\d{17}(\d|X|x)$/;
return regex.test(id);
}
原因:校验码计算错误。 解决方法:
function calculateCheckCode(id) {
const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const checkCodes = ['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];
}
return checkCodes[sum % 11];
}
function isValidCheckCode(id) {
const lastChar = id.charAt(17).toUpperCase();
return lastChar === calculateCheckCode(id);
}
原因:输入的出生日期不符合实际。 解决方法:
function isValidBirthDate(id) {
const birthDateStr = id.substring(6, 14);
const birthDate = new Date(birthDateStr);
return !isNaN(birthDate.getTime()) && birthDateStr === birthDate.toISOString().substring(0, 10);
}
function validateIDCard(id) {
if (!isValidFormat(id)) return false;
if (!isValidBirthDate(id)) return false;
if (!isValidCheckCode(id)) return false;
return true;
}
// 使用示例
const idCard = "11010519491231002X";
console.log(validateIDCard(idCard)); // 输出: true 或 false
通过上述方法,可以有效校验身份证号码的正确性,确保数据的准确性和安全性。
领取专属 10元无门槛券
手把手带您无忧上云