驗證身份證的合法性JS代碼

驗證身份證的有效性:

function checkIdcard(value){
 var idcard = value;
 if(idcard==""){
  return true;
 }
 var regex1 = /^[1-9][0-7]\d{4}((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229))\d{3}(\d|X|x)?$/;
 /*身份號碼位數及格式檢驗*/
 switch (idcard.length) {
   case 15:
  if ( (parseInt(idcard.substr(6,2))+1900) % 4 == 0 || ((parseInt(idcard.substr(6,2))+1900) % 100 == 0 && (parseInt(idcard.substr(6,2))+1900) % 4 == 0 )){
   var regex2 = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;//測試出生日期的合法性
  } else {
   var regex2 = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;//測試出生日期的合法性
  }
  if(regex2.test(idcard))
   return true;
  else
   return false;
  break;
   case 18:
    if(regex1.test(idcard)){
   var S = (parseInt(idcard.charAt(0)) + parseInt(idcard.charAt(10))) * 7 +
                (parseInt(idcard.charAt(1)) + parseInt(idcard.charAt(11))) * 9 +
                (parseInt(idcard.charAt(2)) + parseInt(idcard.charAt(12))) * 10 +
                (parseInt(idcard.charAt(3)) + parseInt(idcard.charAt(13))) * 5 +
                (parseInt(idcard.charAt(4)) + parseInt(idcard.charAt(14))) * 8 +
                (parseInt(idcard.charAt(5)) + parseInt(idcard.charAt(15))) * 4 +
                (parseInt(idcard.charAt(6)) + parseInt(idcard.charAt(16))) * 2 +
                parseInt(idcard.charAt(7)) * 1 +
                parseInt(idcard.charAt(8)) * 6 +
                parseInt(idcard.charAt(9)) * 3;
            var Y = S % 11;
   var M = "F";
   var JYM = "10X98765432";
   M = JYM.substr(Y, 1);
   /*判斷校驗位*/
   if (M == idcard.charAt(17).toUpperCase()) {
         //alert(Errors[0]+"18");
    return true;
   } else {
    //alert(Errors[3]);
    //showErrMsg = Errors[3];
    return false;
   }
  }else{
   return false;
  }
  break;
   default:
    //alert(Errors[1]);
  //showErrMsg = Errors[1];
  return false;
 }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章