Java進行身份證格式強校驗(准)


最近做了一個系統,涉及到對用戶輸入的身份證號進行校驗,減少臟數據傳入后台處理並降低企業驗證成本,因此在接入層便對輸入信息做格式強校驗。

 

直接附上代碼,可直接使用。

 

 1 package hope.identitycodecheck.demo;
 2 
 3 import java.text.DateFormat;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 /**
 7  * 
 8  * @author hp
 9  * 
10  * */
11 public class IdentityCodeUtil {
12     /**
13      * 身份證號校驗 (支持18位)
14      * 
15      * */
16     public static boolean checkIdentityCode(String identityCode) {
17         if (!identityCode.matches("\\d{17}(\\d|x|X)$")) {
18             return false;
19         }
20         Date d = new Date();
21         DateFormat df = new SimpleDateFormat("yyyyMMdd");
22         int year = Integer.parseInt(df.format(d));
23         if (Integer.parseInt(identityCode.substring(6, 10)) < 1900 || Integer.parseInt(identityCode.substring(6, 10)) > year) {// 7-10位是出生年份,范圍應該在1900-當前年份之間
24             return false;
25         }
26         if (Integer.parseInt(identityCode.substring(10, 12)) < 1 || Integer.parseInt(identityCode.substring(10, 12)) > 12) {// 11-12位代表出生月份,范圍應該在01-12之間
27             return false;
28         }
29         if (Integer.parseInt(identityCode.substring(12, 14)) < 1 || Integer.parseInt(identityCode.substring(12, 14)) > 31) {// 13-14位是出生日期,范圍應該在01-31之間
30             return false;
31         }
32         // 校驗第18位
33         // S = Sum(Ai * Wi), i = 0, ... , 16 ,先對前17位數字的權求和
34         // Ai:表示第i位置上的身份證號碼數字值
35         // Wi:表示第i位置上的加權因子
36         // Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
37         String[] tempA = identityCode.split("|");
38         int[] a = new int[18];
39         for (int i = 0; i < tempA.length - 2; i++) {
40             a[i] = Integer.parseInt(tempA[i + 1]);
41         }
42         int[] w = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; // 加權因子
43         int sum = 0;
44         for (int i = 0; i < 17; i++) {
45             sum = sum + a[i] * w[i];
46         }
47         // Y = mod(S, 11)
48         // 通過模得到對應的校驗碼
49         // Y: 0 1 2 3 4 5 6 7 8 9 10
50         // 校驗碼: 1 0 X 9 8 7 6 5 4 3 2
51         String[] v = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" }; // 校驗碼
52         int y = sum % 11;
53         if (!v[y].equalsIgnoreCase(identityCode.substring(17))) {// 第18位校驗碼錯誤
54             return false;
55         }
56         return true;
57     }
58     
59 
60     public static void main(String[] args) {
61         System.out.println(checkIdentityCode("110110198001019719"));
62     }
63 }

 

希望可以為大家提供方便和幫助。

 


免責聲明!

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



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