身份證校驗:根據正則 +十七位數字本體碼權重

此種校驗,一般隨意輸入的身份證,都不能通過

public static final String CERT_CODE_18_REG = "/^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
public static final String VALIDATION_SUCCESS = "";
private static final Pattern ID_18_PATTERN = Pattern.compile(CERT_CODE_18_REG);
/**
 * 校驗身份證號碼
 * 
 * @param certCode
 * @return
 */
public static String checkCertCode(String certCode) {
   if (certCode == null || certCode.isEmpty()) {
      return "身份證號不能爲空";
   }
   if (certCode.length() == 15) {
      // 長度爲15位的匹配15位正則表達式
      Matcher matcher = ID_15_PATTERN.matcher(certCode);
      if (matcher.matches()) {
         return VALIDATION_SUCCESS;
      } else {
         return "身份證號[" + certCode + "]格式不正確";
      }
   } else if (certCode.length() == 18) {
      // 長度爲18位的匹配18位正則表達式
      Matcher matcher = ID_18_PATTERN.matcher(certCode);
      if (matcher.matches()) {
         // 根據17位本位碼計算出校驗碼
         char checkCode = getValidateCode(certCode.substring(0, certCode.length() - 1));
         // 根據身份證號截取最後一位數字
         char key = certCode.charAt(certCode.length() - 1);
         if (checkCode != key) {
            return "身份證號[" + certCode + "]不合法";
         }
      } else {
         return "身份證號[" + certCode + "]格式不正確";
      }
   } else {
      return "身份證號[" + certCode + "]格式不正確";
   }
   return VALIDATION_SUCCESS;
}
public char getValidateCode(String id17) {
   // 十七位數字本體碼權重
   int[] weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
   // mod11,對應校驗碼字符值
   char[] validate = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
   int sum = 0;
   int mode;
   for (int i = 0; i < id17.length(); i++) {
      sum = sum + Integer.parseInt(String.valueOf(id17.charAt(i))) * weight[i];
   }
   mode = sum % 11;
   return validate[mode];
}

 

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