此种校验,一般随意输入的身份证,都不能通过
public static final String CERT_CODE_18_REG = "/^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
public static final String VALIDATION_SUCCESS = "";
private static final Pattern ID_18_PATTERN = Pattern.compile(CERT_CODE_18_REG);
/** * 校验身份证号码 * * @param certCode * @return */
public static String checkCertCode(String certCode) {
if (certCode == null || certCode.isEmpty()) {
return "身份证号不能为空";
}
if (certCode.length() == 15) {
// 长度为15位的匹配15位正则表达式
Matcher matcher = ID_15_PATTERN.matcher(certCode);
if (matcher.matches()) {
return VALIDATION_SUCCESS;
} else {
return "身份证号[" + certCode + "]格式不正确";
}
} else if (certCode.length() == 18) {
// 长度为18位的匹配18位正则表达式
Matcher matcher = ID_18_PATTERN.matcher(certCode);
if (matcher.matches()) {
// 根据17位本位码计算出校验码
char checkCode = getValidateCode(certCode.substring(0, certCode.length() - 1));
// 根据身份证号截取最后一位数字
char key = certCode.charAt(certCode.length() - 1);
if (checkCode != key) {
return "身份证号[" + certCode + "]不合法";
}
} else {
return "身份证号[" + certCode + "]格式不正确";
}
} else {
return "身份证号[" + certCode + "]格式不正确";
}
return VALIDATION_SUCCESS;
}
public char getValidateCode(String id17) {
// 十七位数字本体码权重
int[] weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
// mod11,对应校验码字符值
char[] validate = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
int sum = 0;
int mode;
for (int i = 0; i < id17.length(); i++) {
sum = sum + Integer.parseInt(String.valueOf(id17.charAt(i))) * weight[i];
}
mode = sum % 11;
return validate[mode];
}
本文详细介绍了一种用于校验身份证号码有效性的算法,包括针对15位和18位身份证号码的正则表达式匹配,以及18位身份证号码中校验码的计算方法。该算法能够准确判断身份证号码是否符合中国身份证号的标准格式。
402

被折叠的 条评论
为什么被折叠?



