身份證校驗(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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM