身份证校验:根据正则 +十七位数字本体码权重

此种校验,一般随意输入的身份证,都不能通过

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];
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值