身份证号校验

@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("证件号码不符合规则");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小松の博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值