package com.tourguide.common.validation;
|
|
import java.time.DateTimeException;
|
import java.time.LocalDate;
|
import java.time.format.DateTimeFormatter;
|
|
/** 中国大陆18位居民身份证号码格式与校验位验证工具。 */
|
public final class ChineseIdCardValidator {
|
private static final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
|
private static final char[] CHECK_CODES = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
|
private static final DateTimeFormatter BIRTHDAY_FORMATTER = DateTimeFormatter.BASIC_ISO_DATE;
|
|
private ChineseIdCardValidator() {}
|
|
public static boolean isValid(String idCardNo) {
|
if (idCardNo == null) { return false; }
|
String value = idCardNo.trim().toUpperCase();
|
if (!value.matches("^[1-9]\\d{16}[0-9X]$")) { return false; }
|
try {
|
LocalDate birthday = LocalDate.parse(value.substring(6, 14), BIRTHDAY_FORMATTER);
|
if (birthday.isAfter(LocalDate.now())) { return false; }
|
} catch (DateTimeException exception) {
|
return false;
|
}
|
int sum = 0;
|
for (int index = 0; index < WEIGHTS.length; index++) {
|
sum += (value.charAt(index) - '0') * WEIGHTS[index];
|
}
|
return value.charAt(17) == CHECK_CODES[sum % 11];
|
}
|
}
|