新旧身份证合法性验证及相互转换算法(二):JavaScript身份证号码验证-支持新的带x身份证...

xiaoxiao2024-10-26  17

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>身份证号码验证-支持新的带x身份证</title><script language="javascript">//身份证号码验证-支持新的带x身份证//function check_ID_card() { var ID_card = document.all('idcard').value; var IDcardLen = ID_card.length; var fMod = 11; //身份证算法求模关键值 var oldIDLen = 15; //旧身份证长度 var newIDLen = 18; //新身份证长度 var yearFlag = "19"; //新身份证年份标志 var Wi = new Array(); //位权值数组 var varArray = new Array(); var birthday = ''; //生日 var checkDigit = ''; //校验位 var numSum = 0; //数字和 var regStr = /^\d{15,17}([\dxX]{1})?$/; if ((IDcardLen != 15) && (IDcardLen != 18)) { alert("身份证长度必须为15或18位."); return false; } if(!regStr.test(ID_card)){ alert("身份证号码必须为数字(18位的新身份证最后一位可以是x)."); return false; } if(IDcardLen == 15){ birthday = "19" + ID_card.substring(6,8) + "-" + ID_card.substring(8,10) + "-" + ID_card.substring(10,12); }else{ birthday = ID_card.substring(6,10) + "-" + ID_card.substring(10,12) + "-" + ID_card.substring(12,14); } if(!isDate(birthday)){ alert("身份证号码中的日期格式不对(第6-12位)."); return false; } if(IDcardLen == 18){ for(var i=0;i<newIDLen-1;i++){ var k = Math.pow(2,newIDLen-1-i); Wi[i] = k % 11; } for(var i=0;i<IDcardLen-1;i++){ varArray[i] = ID_card.charAt(i); varArray[i] = varArray[i]*Wi[i]; numSum = numSum + varArray[i]; } checkDigit = 12 - numSum % 11; switch (checkDigit) { case 10: checkDigit = 'X'; break; case 11: checkDigit = 0; break; case 12: checkDigit = 1; break; } // check last digit if (ID_card.charAt(17).toUpperCase() != checkDigit) { alert("身份证最后一位校验码不对,应该为"+checkDigit+"."); return false; } } alert(ID_card+"为正确的身份证号码."); return true;}//日期格式验证(yyyy-mm-dd,其中月,日可以只有一位)//function isDate(dateStr){ var B, D=0; // Split into $1 $2 $3 B = /^(\d{4})-(\d|\d\d)-(\d|\d\d)$/.test(dateStr); if (B) with (RegExp){ // $1 $2 $3 = Y M D D = new Date($1, $2-1, $3); // test Y M D valid B = ((D.getMonth()==$2-1) && (D.getFullYear()==$1)); } return B;}</script></head><body> <form name='frm' onSubmit="check_ID_card();return false;"> <center> 身份证号码:<input type='text' name='idcard' value="">   <input type=submit value='验证'> </center> </form></body></html>
转载请注明原文地址: https://www.6miu.com/read-5018588.html

最新回复(0)