<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>42度空间-身份证号码的正则表达式及验证详解-校验码测试</title>
</head>
<body>
<div id="main"></div>
<script>
    console.log = function(val) {
        document.getElementById("main").innerHTML += val +"<br />";
    }
    var checkCode = function (val) {
        var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
        var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
        var code = val.substring(17);
        if(p.test(val)) {
            var sum = 0;
            for(var i=0;i<17;i++) {
                sum += val[i]*factor[i];
            }
            if(parity[sum % 11] == code.toUpperCase()) {
                return true;
            }
        }
        return false;
    }
    // 输出 true, 校验码相符
    console.log(checkCode("11010519491231002X"));
    // 输出 false, 校验码不符
    console.log(checkCode("110105194912310021"));
</script>
</body>
</html>