Java判斷身份證號碼是否正確
阿新 • • 發佈:2019-01-24
方法如下:
public static final int IDENTITYCODE_OLD = 15; // 老身份證15位 public static final int IDENTITYCODE_NEW = 18; // 新身份證18位 public static int[] Wi = new int[17]; /** * 判斷身份證號碼是否正確。 * * @param code * 身份證號碼。 * @return 如果身份證號碼正確,則返回true,否則返回false。 */ public static boolean isIdentityCode(String code) { if (StringUtils.isEmpty(code)) { return false; } String birthDay = ""; code = code.trim().toUpperCase(); // 長度只有15和18兩種情況 if ((code.length() != IDENTITYCODE_OLD) && (code.length() != IDENTITYCODE_NEW)) { return false; } // 身份證號碼必須為數字(18位的新身份證最後一位可以是x) Pattern pt = Pattern.compile("(^\\d{15}$)|(\\d{17}(?:\\d|x|X)$)"); Matcher mt = pt.matcher(code); if (!mt.find()) { return false; } // 驗證生日 if (code.length() == IDENTITYCODE_OLD) { birthDay = "19" + code.substring(6, 12); } else { birthDay = code.substring(6, 14); } if (DateUtils.dateFormatToDate(birthDay, "yyyyMMdd") == null) { return false; } // 最後一位校驗碼驗證 if (code.length() == IDENTITYCODE_NEW) { String lastNum = getCheckFlag(code.substring(0, IDENTITYCODE_NEW - 1)); // check last digit if (!("" + code.charAt(IDENTITYCODE_NEW - 1)).toUpperCase().equals( lastNum)) { return false; } } return true; }