好的,以下是一个用 JavaScript 验证身份证号前 17 位为数字,并自动识别出生日期和性别的代码示例:
function checkID(id) {
if (!/^\d{17}(\d|x)$/i.test(id)) {
console.log('身份证号码格式错误');
return false;
}
let birthYear = id.substring(6, 10);
let birthMonth = id.substring(10, 12);
let birthDate = id.substring(12, 14);
let date = new Date(birthYear + '-' + birthMonth + '-' + birthDate);
if (date.getFullYear() != birthYear ||
date.getMonth() != birthMonth - 1 ||
date.getDate() != birthDate) {
console.log('身份证号码出生日期错误');
return false;
}
let sex = id.substring(16, 17) % 2 == 0 ? '女' : '男';
console.log('出生日期:' + birthYear + '年' + birthMonth + '月' + birthDate + '日');
console.log('性别:' + sex);
return true;
}