# Java 校验身份证号码

📆 2021-12-30 16:00

# Java 版

public static boolean testIdCard(String idCard){
    if(idCard==null||idCard.length()!=18) return false;

    String idCardTest=idCard.toUpperCase();

    Pattern p=Pattern.compile("[0-9X]{18}");
    Matcher m=p.matcher(idCardTest);
    if(!m.matches()) return false;

    final int[] w=new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    final char[] c=new char[]{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
    int sum=0;
    for (int i = 0; i < idCardTest.length()-1; i++) {
        sum+=Character.getNumericValue(idCardTest.charAt(i))*w[i];
    }
    return c[sum%11]==idCardTest.charAt(17);
}

# JavaScript 版

var idcard='410185********3535';
var w=[7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var c=['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
var sum=0;
for(var i=0;i<idcard.length-1;i++){
    sum+=parseInt(idcard.charAt(i))*w[i];
}
console.log(c[sum%11]==idcard[idcard.length-1]);

JavaScript 版比较简陋,可参考 Java 版进行增强

最后更新于: 12/30/2021, 4:21:10 PM