一個完整校驗身份證
阿新 • • 發佈:2018-11-04
一個完整校驗身份證
/** * 校驗身份證號合法性 */ function checkIdNumberValid(tex){ var tip = '輸入的身份證號有誤,請檢查後重新輸入!'; var num = tex.value; num = num.toUpperCase(); var len, re; len = num.length; if(len == 0) return true; //身份證號碼為15位或者18位,15位時全為數字,18位前17位為數字,最後一位是校驗位,可能為數字或字元X。 if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))){ alert(tip); tex.focus(); return false; } //驗證前兩位地區是否有效 var aCity= {11:"北京",12:"天津",13:"河北",14:"山西",15:"內蒙古",21:"遼寧",22:"吉林",23:"黑龍江 ",31:"上海", 32:"江蘇",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山東",41:"河南",42:"湖北 ",43:"湖南", 44:"廣東",45:"廣西",46:"海南",50:"重慶",51:"四川",52:"貴州",53:"雲南",54:"西藏 ",61:"陝西", 62:"甘肅",63:"青海",64:"寧夏",65:"新疆",71:"臺灣",81:"香港",82:"澳門",91:"國外 "} if(aCity[parseInt(num.substr(0,2))] == null){ alert(tip); tex.focus(); return false; } //當身份證為15位時的驗證出生日期。 if (len == 15){ re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/); var arrSplit = num.match(re); //檢查生日日期是否正確 var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]); var bGoodDay; bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4])); if (!bGoodDay){ alert(tip); tex.focus(); return false; } } //當身份證號為18位時,校驗出生日期和校驗位。 if (len == 18){ re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/); var arrSplit = num.match(re); //檢查生日日期是否正確 var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]); var bGoodDay; bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4])); if (!bGoodDay){ alert(tip); tex.focus(); return false; } else{ //檢驗18位身份證的校驗碼是否正確。 //校驗位按照ISO 7064:1983.MOD 11-2的規定生成,X可以認為是數字10。 var valnum; var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); var nTemp = 0, i; for(i = 0; i < 17; i ++){ nTemp += num.substr(i, 1) * arrInt[i]; } valnum = arrCh[nTemp % 11]; if (valnum != num.substr(17, 1)){ alert(tip); tex.focus(); return false; } } } return true; }