@Override
public void isIdCardNo(String identityCode) {
Boolean flag = true;
if (!identityCode.matches("\\d{17}(\\d|x|X)$")) {
throw new RuntimeException("证件号码不符合规则");
}
if (identityCode.length() < 7) {
throw new RuntimeException("证件号码不符合规则");
}
Date d = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMdd");
int year = Integer.parseInt(df.format(d));
// 7-10位是出生年份,范围应该在1900-当前年份之间
if (Integer.parseInt(identityCode.substring(6, 10)) < 1900 || Integer.parseInt(identityCode.substring(6, 10)) > year) {
flag = false;
}
// 11-12位代表出生月份,范围应该在01-12之间
if (Integer.parseInt(identityCode.substring(10, 12)) < 1 || Integer.parseInt(identityCode.substring(10, 12)) > 12) {
flag = false;
}
// 13-14位是出生日期,范围应该在01-31之间
if (Integer.parseInt(identityCode.substring(12, 14)) < 1 || Integer.parseInt(identityCode.substring(12, 14)) > 31) {
flag = false;
}
/*
校验第18位
S = Sum(Ai * Wi), i = 0, ... , 16 ,先对前17位数字的权求和
Ai:表示第i位置上的身份证号码数字值
Wi:表示第i位置上的加权因子
Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
*/
String[] tempA = identityCode.split("|");
int[] a = new int[18];
for (int i = 0; i < tempA.length - 2; i++) {
a[i] = Integer.parseInt(tempA[i + 1]);
}
int[] w = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 加权因子
int sum = 0;
for (int i = 0; i < 17; i++) {
sum = sum + a[i] * w[i];
}
/*
Y = mod(S, 11)
通过模得到对应的校验码
Y: 0 1 2 3 4 5 6 7 8 9 10
校验码: 1 0 X 9 8 7 6 5 4 3 2
*/
String[] v = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" }; // 校验码
int y = sum % 11;
if (!v[y].equalsIgnoreCase(identityCode.substring(17))) {// 第18位校验码错误
flag = false;
}
if(!flag){
throw new RuntimeException("证件号码不符合规则");
}
}
身份证号校验
于 2024-04-10 09:04:48 首次发布