身份证验证
function checkIdCard(id){
var result=null;
var regExp = /^[a-zA-Z][0-9]{6}\([\w]{1}\)$/ ; //用于匹配香港身份证
if (id.length == 15) {
result=id.match('\^(11|12|31|51|15|65|54|64|45|81|82|23|22|21|13|14|63|37|41|32|34|35|36|43|42|44|46|62|61|51|52|53|71|33|50)\\d{13}$');
if(null==result){
return '身份证号有误!';
}
return null;
} else if (id.length == 18) {
result=id.match("\^(11|12|31|51|15|65|54|64|45|81|82|23|22|21|13|14|63|37|41|32|34|35|36|43|42|44|46|62|61|51|52|53|71|33|50)\\d{15}[Xx0-9]$");
if(null==result){
return '身份证号有误!';
}
var check = 0;
var checkNum = new Array(2, 4, 8, 5, 10, 9, 7, 3, 6, 1, 2, 4, 8, 5, 10, 9, 7);
var checkNum2 = new Array( "1", "0", "X", "9", "8", "7", "6", "5", "4","3", "2" );
for (var i = 0; i < 17; i++) {
check += id.substring(16-i,17-i) * checkNum[i];
}
if(checkNum2[(check % 11)]!=id.substring(17,18)){
return '身份证号有误!';
}
return null;
}else if(regExp.test(id)){
return null
}
else {
return '身份证号有误!';
}
}
/**
* @ 身份证号生日年份
* 421022198810064521 => 1988
* 421022881006452 => 1988
*/
function getBirthdayYearFromIdCard(idCard){
if (idCard == undefined) {
return null;
}
if (idCard.length == 15) {
return "19" + idCard.substring(6, 8);
}
if (idCard.length == 18) {
return idCard.substring(6, 10);
}
return null;
}
/**
* @ 身份证号生日月份
* 421022198810064521 => 10
* 421022881006452 => 10
*/
function getBirthdayMonthFromIdCard(idCard){
if (idCard == undefined) {
return null;
}
if (idCard.length == 15) {
return idCard.substring(8, 10);
}
if (idCard.length == 18) {
return idCard.substring(10, 12);
}
return null;
}
/**
* @ 身份证号生日月份
* 421022198810064521 => 10
* 421022881006452 => 10
*/
function getBirthdayDayFromIdCard(idCard){
if (idCard == undefined) {
return null;
}
if (idCard.length == 15) {
return idCard.substring(10, 12);
}
if (idCard.length == 18) {
return idCard.substring(12, 14);
}
return null;
}
/**
* @ 身份证号与生日效验
*/
function checkIdCardAndBirthday(idCard, birthday){
var idCardResult = checkIdCard(idCard);
if (idCardResult == null && birthday != '') {
var yearFromIdCard = getBirthdayYearFromIdCard(idCard);
var monthFromIdCard = getBirthdayMonthFromIdCard(idCard);
var dayFromIdCard = getBirthdayDayFromIdCard(idCard);
var birthday_year = birthday.substring(0, 4);
var birthday_month = birthday.substring(5, 7);
var birthday_day = birthday.substring(8, 10);
if (yearFromIdCard != birthday_year) {
return "出生年份与身份证不符。";
}
if (monthFromIdCard != birthday_month) {
return "出生月份与身份证不符。";
}
if (dayFromIdCard != birthday_day) {
return "出生日期与身份证不符。";
}
}
return null;
}