身份证校验(java)

判断是第几代身份证(第一代15位, 第二代18位)

 1 if (cardId.length() == 15 || cardId.length() == 18) {
 2     if (!this.cardCodeVerifySimple(cardId)) {
 3         error.put("cardId", "15位或18位身份证号码不正确");
 4     } else {
 5         if (cardId.length() == 18 && !this.cardCodeVerify(cardId)) {
 6             error.put("cardId", "18位身份证号码不符合国家规范");
 7         }
 8     }
 9 } else {
10     error.put("cardId", "身份证号码长度必须等于15或18位");
11 }

正则校验身份证是否符合第一代第二代标准

 1 private boolean cardCodeVerifySimple(String cardcode) {
 2     //第一代身份证正则表达式(15位)
 3     String isIDCard1 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
 4     //第二代身份证正则表达式(18位)
 5     String isIDCard2 ="^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[A-Z])$";
 6 
 7     //验证身份证
 8     if (cardcode.matches(isIDCard1) || cardcode.matches(isIDCard2)) {
 9         return true;
10     }
11     return false;
12 }

验证第二代身份证是否符合国家规范

 1 private boolean cardCodeVerify(String cardcode) {
 2     int i = 0;
 3     String r = "error";
 4     String lastnumber = "";
 5 
 6     i += Integer.parseInt(cardcode.substring(0, 1)) * 7;
 7     i += Integer.parseInt(cardcode.substring(1, 2)) * 9;
 8     i += Integer.parseInt(cardcode.substring(2, 3)) * 10;
 9     i += Integer.parseInt(cardcode.substring(3, 4)) * 5;
10     i += Integer.parseInt(cardcode.substring(4, 5)) * 8;
11     i += Integer.parseInt(cardcode.substring(5, 6)) * 4;
12     i += Integer.parseInt(cardcode.substring(6, 7)) * 2;
13     i += Integer.parseInt(cardcode.substring(7, 8)) * 1;
14     i += Integer.parseInt(cardcode.substring(8, 9)) * 6;
15     i += Integer.parseInt(cardcode.substring(9, 10)) * 3;
16     i += Integer.parseInt(cardcode.substring(10,11)) * 7;
17     i += Integer.parseInt(cardcode.substring(11,12)) * 9;
18     i += Integer.parseInt(cardcode.substring(12,13)) * 10;
19     i += Integer.parseInt(cardcode.substring(13,14)) * 5;
20     i += Integer.parseInt(cardcode.substring(14,15)) * 8;
21     i += Integer.parseInt(cardcode.substring(15,16)) * 4;
22     i += Integer.parseInt(cardcode.substring(16,17)) * 2;
23     i = i % 11;
24     lastnumber =cardcode.substring(17,18);
25     if (i == 0) {
26         r = "1";
27     }
28     if (i == 1) {
29         r = "0";
30     }
31     if (i == 2) {
32         r = "x";
33     }
34     if (i == 3) {
35         r = "9";
36     }
37     if (i == 4) {
38         r = "8";
39     }
40     if (i == 5) {
41         r = "7";
42     }
43     if (i == 6) {
44         r = "6";
45     }
46     if (i == 7) {
47         r = "5";
48     }
49     if (i == 8) {
50         r = "4";
51     }
52     if (i == 9) {
53         r = "3";
54     }
55     if (i == 10) {
56         r = "2";
57     }
58     if (r.equals(lastnumber.toLowerCase())) {
59         return true;
60     }
61     return false;
62 }
原文地址:https://www.cnblogs.com/chinda/p/6093272.html