java验证身份证号

直接上代码

public static boolean checkIDCard(String str) {
   str = trimToEmpty(str).toUpperCase();


if (isEmpty(str)) {
return false;
}


Pattern pattern = Pattern.compile("^\\d{17}(\\d|X)$");
Matcher matcher = pattern.matcher(str);
if (!matcher.matches()) {
return false;
}


   int[] cities = {11,12,13,14,15,21,22,23,31,32,33,33,35,36,37,41,42,43,44,45,46,50,50,52,53,54,61,62,63,64,65,71,81,82,91};
   str = str.replaceAll("X$", "a");
if (Arrays.binarySearch(cities, Integer.parseInt(str.substring(0, 2))) < 0) {
return false;
}


String sBirthday = str.substring(6, 10) + "-" + Integer.parseInt(str.substring(10, 12)) + "-" + Integer.parseInt(str.substring(12, 14));
Calendar cal = Calendar.getInstance();
try {
cal.setTime(new SimpleDateFormat("yyyy/MM/dd").parse(sBirthday.replaceAll("-", "/")));
} catch (ParseException e) {
e.printStackTrace();
}
if (!sBirthday.equals(cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH))) {
return false;
}


int nSum = 0;
for (int i = 17; i >= 0; i--) {
String c = new Character(str.charAt(17 - i)).toString();
nSum += (Math.pow(2, i) % 11) * Integer.parseInt("a".equals(c) ? "10" : c);
}


if (nSum % 11 != 1) {
return false;
}
return true;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值