JAVA后台验证身份证是否合法

这里需要针对身份证号是15位还是18位进行不同的验证,当然这里只是对身份证号码进行并不是那么严格的验证,列位看官各取所需吧

    /**
     * 检查身份证号码合法性
     * @param idCardNo
     * @return
     * @throws Exception
     */
    public boolean checkIdCardNo(String idCardNo) throws Exception{
        try {
            if(StringUtils.isBlank(idCardNo)){
                return false;
            }
            int length = idCardNo.length();
            if(length == 15){
                Pattern p = Pattern.compile("^[0-9]*$");
                Matcher m = p.matcher(idCardNo);
                return m.matches();
            }else if(length == 18){
                String front_17 = idCardNo.substring(0, idCardNo.length() - 1);//号码前17位
                String verify = idCardNo.substring(17, 18);//校验位(最后一位)
                Pattern p = Pattern.compile("^[0-9]*$");
                Matcher m = p.matcher(front_17);
                if(!m.matches()){
                    return false;
                }else{
                    this.checkVerify(front_17, verify);
                }
            }
            return false;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 校验验证位合法性
     * @param front_17
     * @param verify
     * @return
     * @throws Exception
     */
    public static boolean checkVerify(String front_17,String verify) throws Exception{
        try {
            int[] wi = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1};
            String[] vi = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
            int s = 0;
            for(int i = 0; iint ai = Integer.parseInt(front_17.charAt(i) + "");
                s += wi[i]*ai;
            }
            int y = s % 11;
            String v = vi[y];
            if(!(verify.toUpperCase().equals(v))){
                return false;
            }
            return true;
        } catch (Exception e) {
            throw e;
        }
    }

你可能感兴趣的:(JAVA-WEB)