身份证校验工具

来自:一名小小程序员

本文主要讲述:身份证校验器,主要校验身份证的合法性。

身份证号码校验规则:

1、身份证号码是18位数,分别是17位数字和1位校验码。

具体含义分别是:6位地址码+8位出生日期+3位顺序码+1位校验码,校验码可能为字母

2、顺序码如果是奇数代表男性,偶数代表女性。

3、最后1位校验码是根据前17位数字算出来的

       import java.util.stream.IntStream;
       
       public class CheckIdcardUtils{

        // 身份证校验码
		private static final int[] COEFFICIENT_ARRAY = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
		// 身份证号的尾数规则
		private static final String[] IDENTITY_MANTISSA = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
		private static final String IDENTITY_PATTERN = "^[0-9]{17}[0-9Xx]$";

		//校验身份证号是否合法
		public static boolean isLegalPattern(String identity) {
			if (identity == null || identity.length() != 18 || !identity.matches(IDENTITY_PATTERN)) {
				return false;
			}
			char[] chars = identity.toCharArray();
			long sum = IntStream.range(0, 17).map(index -> {
				char ch = chars[index];
				int digit = Character.digit(ch, 10);
				int coefficient = COEFFICIENT_ARRAY[index];
				return digit * coefficient;
			}).summaryStatistics().getSum();
			String mantissa = IDENTITY_MANTISSA[(int) (sum % 11)];
			if (identity.substring(17).equalsIgnoreCase(mantissa)) {
				return true;
			} else {
				return false;
			}
		}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值