首页 > 编程语言 > 详细

Java实现身份证号码校验

时间:2017-04-13 10:09:13      阅读:992      评论:0      收藏:0      [点我收藏+]

二话不说,直接上代码。

 

 

/**
     * 校验18位身份证号
     * 
     * @param identityCode
     * 
     * 返回true则表示校验通过
     */
    public boolean checkIdentityCode(String identityCode) {
        // 校验身份证位数为18位
        if (!identityCode.matches("\\d{17}(\\d|x|X)$")) {
            return false;
        }
        Date d = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        int year = Integer.parseInt(df.format(d));
        if (Integer.parseInt(identityCode.substring(6, 10)) < 1900
                || Integer.parseInt(identityCode.substring(6, 10)) > year) {// 7-10位是出生年份,范围应该在1900-当前年份之间
            return false;
        }
        if (Integer.parseInt(identityCode.substring(10, 12)) < 1
                || Integer.parseInt(identityCode.substring(10, 12)) > 12) {// 11-12位代表出生月份,范围应该在01-12之间
            return false;
        }
        if (Integer.parseInt(identityCode.substring(12, 14)) < 1
                || Integer.parseInt(identityCode.substring(12, 14)) > 31) {// 13-14位是出生日期,范围应该在01-31之间
            return 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位校验码错误
            return false;
        }
        return true;
    }

 

Java实现身份证号码校验

原文:http://www.cnblogs.com/orionhp/p/6702544.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!