liujie
2026-07-29 c560a88ab429cd164d8eb6fcec42a273b898e230
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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];
    }
}