Skip to content

Instantly share code, notes, and snippets.

@GZShi
Created November 8, 2013 10:24
Show Gist options
  • Save GZShi/7369112 to your computer and use it in GitHub Desktop.
Save GZShi/7369112 to your computer and use it in GitHub Desktop.
根据 GB11643-1999 的规则对身份证号码正确性进行校验
/*
* 根据GB11643-1999的规则对身份证号码正确性进行校验
* 如果身份证中的日期信息在系统时间之后,也不能通过校验
*/
function checkChineseID(id) {
id += '';
if(/^\d{15}(\d\d[0-9X])?$/.test(id)) {
var year = 0,
month = 0,
day = 0,
code = 0,
sum = 0,
weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
modTable = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'],
mList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
bits = id.split(''),
now = (new Date()).getTime(),
idTime = 0;
if(id.length == 15) {
year = parseInt(id.substr(6, 2)) + 1900;
month = parseInt(id.substr(8, 2));
day = parseInt(id.substr(10, 2));
} else {
year = parseInt(id.substr(6, 4));
month = parseInt(id.substr(10, 2));
day = parseInt(id.substr(12, 2));
// 获取18位身份证的最后一位校验码
code = bits[bits.length - 1];
// 按照GB11643-1999中的规则计算校验和
for(var i = 0, len = bits.length - 1; i < len; ++i) {
sum += weight[i] * parseInt(bits[i]);
}
sum = sum % 11;
if(code !== modTable[sum]) {
return '身份证号码校验位错误!最后一位应该是:' + modTable[sum];
}
}
// 根据年份对每月天数进行校正
mList[1] = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) ? 29 : 28;
// 获取身份证上日期
idTime = (new Date([year, month, day].join('-'))).getTime();
// 对日期的格式和正确性进行校验
if(day <= 0 || day > mList[month - 1] || month <= 0 || month > 12) {
return '身份证日期位格式错误';
} else if(isNaN(idTime) || idTime >= now){
return '身份证日期位格式错误或内容不正确';
} else {
return true;
}
} else {
if(/^\d{17}[0-9x]$/.test(id)) {
return '提示:身份证最后一位应该为“X”';
} else {
return '身份证格式错误,请输入15位或17位身份证号码。';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment