# 身份證號合法性校驗

public static boolean isLegalIDCard(String idCard) {
boolean res = false;
if (!StringUtils.isBlank(idCard)) {
// 校驗規則(15或是18位身份證號碼)
String regex = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]\$)|" + "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}\$)";
boolean matches = idCard.matches(regex);
// 判斷第18位校驗值
if (matches) {
if (idCard.length() == 18) {
char[] idCardArray = idCard.toCharArray();
// 前十七位加權因子
int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
// 除以11後,可能產生的11位餘數對應的驗證碼
String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
int total = 0;
for (int i = 0; i < idCardWi.length; i++) {
int count = Integer.parseInt(String.valueOf(idCardArray[i])) * idCardWi[i];
total += count;
}
// 最後一位校驗碼
int idCardModify = total % 11;
if (idCardY[idCardModify].toUpperCase().equals(String.valueOf(idCardArray[17]).toUpperCase())) {
res = true;
} else {
System.out.println(idCardY[idCardModify].toUpperCase());
res = false;
}
} else {
res = true;
}
}
}
return res;
}