JAVA 身份证校验

身份证校验最重要的是对应的正则表达式

 //正则表达式
   public static   String  strRule="^[1-9][0-7]\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$";

 下面提供两种验证方法代码如下



public class CheckIDCard {

    private Context mContext;
    //正则表达式
   public static   String  strRule="^[1-9][0-7]\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$";
    public CheckIDCard(Context context) {
        mContext = context;
    }

    /** 校验身份证 */
    public static Pattern idNumPattern = Pattern.compile(strRule);
    /** 身份证最后一位校验位 */
    public static String[] ID_JIAO_YAN = new String[] { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };
    /** 身份证前17位系数 */
    public static int[] ID_XI_SHU = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };




    public boolean checkIDCard(String ID){
        if(calculIDLast(ID)){
            /**校验身份证格式*/
            return idNumPattern.matcher(ID).matches();
        }else {
            return false;
        }
    }
    /**
     * 计算身份证最后一位是否正确
     * @return
     */
    private boolean calculIDLast(String ID) {
        boolean flag = false;
        if(ID.length()<18){
            showToast("请输入正确的二代身份证号码");
            return false;
        }
        char[] chars = ID.toCharArray();
        int calculLast=0;
        for (int i=0;i<chars.length-1;i++){
            calculLast += Integer.parseInt(chars[i]+"")*this.ID_XI_SHU[i];
        }
        Log.i("calculLast==",calculLast+"");
        int i = calculLast % 11;
        String a = this.ID_JIAO_YAN[i];
        String b = chars[chars.length-1]+"";
        if (a.toUpperCase().equals(b.toUpperCase())){
            flag = true;
        }
        return flag;
    }
    private void showToast(String msg) {
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }
}

 仅供参考,多多指教,谢谢啦!

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值