首页 > 代码库 > javascript验证香港身份证

javascript验证香港身份证

 1 var assert = require(‘assert‘);
 2 describe(‘test‘, function() {
 3     it(‘coc‘, function() {
 4         var testCard01 = checkHKIDcard("AB987654(2)");
 5         assert(testCard01, true);
 6 
 7         var testCard02 = checkHKIDcard("G123456(A)");
 8         assert.equal(testCard02, true);
 9 
10         var testCard03 = checkHKIDcard("L555555(0)");
11         assert.equal(testCard03, true);
12 
13         var testCard04 = checkHKIDcard("C123456(9)");
14         assert.equal(testCard04, true);
15 
16         var testCard05 = checkHKIDcard("AY987654(A)");
17         assert.equal(testCard05, false);
18 
19     });
20 }) 
21 
22 
23 function checkHKIDcard(str) {
24     var reg = /^[A-Z]{1,2}[0-9]{6}\([0-9A]\)$/
25     if(!str.match(reg)) return false;
26 
27     var temp = str.replace(/[\(\)]/g, ‘‘);
28 
29     var len = temp.length;
30     var sum = (len === 9) 
31               ? 9 * (temp[0].charCodeAt() - 64) + 8 * (temp[1].charCodeAt() - 64)
32               : 8 * (temp[0].charCodeAt() - 64);
33 
34     var arr = temp.split(‘‘).reverse().join(‘‘).substr(1, 6);
35     var arrResult = [2, 3, 4, 5, 6, 7];
36     
37     for(var i = 0; i< arr.length; i++) {
38         sum += Number(arr[i]) * arrResult[i];
39     }
40 
41     var mod = sum % 11;
42     var lastCode = temp[len -1];
43     if(mod === 0 && Number(lastCode) === 0 ) return true;
44     
45     var checkCode = 11 - mod;
46     if(checkCode === 10 && lastCode === ‘A‘) return true;
47     
48     if(checkCode > 0 && checkCode < 10 && Number(lastCode) === checkCode) return true;
49     return false;
50 }

 

javascript验证香港身份证