轉的,比較完善的驗證身份證號的程式碼
1 /* 2 check(ID)驗證身份證號碼 3 返回值:0 : "是正確的身份證號" 4 1 : "身份證校驗不符合求和模11=1這個等式", 5 2 : "身份證最後一位校驗位有誤", 6 3 : "身份證位數不正確", 7 4 : "年份錯誤", 8 5 : "月份錯誤", 9 6 : "日錯誤" 10 11 */ 12 13 function check(ID) { 14 var ck = new IDCard(); 15 ck.check(ID); 16 return ck.errNum; 17 } 18 19 function IDCard(ID) { 20 var me = this; 21 this.checkCode = new Array(1, 0, `X`, 9, 8, 7, 6, 5, 4, 3, 2); 22 this.ID; 23 this.errNum = 0; 24 this.err = { 25 1 : "身份證校驗不符合求和模11=1這個等式", 26 2 : "身份證最後一位校驗位有誤", 27 3 : "身份證位數不正確", 28 4 : "年份錯誤", 29 5 : "月份錯誤", 30 6 : "日錯誤" 31 }; 32 this.err_msg = function() { 33 return (0 !== this.errNum) ? this.err[this.errNum] : null; 34 }; 35 this.check = function(ID) { 36 this.errNum = 0; 37 this.ID = ID; 38 if (cardValidate()) { 39 if (!aiCheck()) this.errNum = 1; 40 if (!LastByteCheck()) this.errNum = 2; 41 return (0 === this.errNum) ? true: false; 42 } else { 43 return false; 44 } 45 }; 46 function getNum(str) { 47 var re = /^[0]*([0-9]*)$/; 48 str.match(re); 49 return parseInt(RegExp.$1,10); 50 } 51 //對身份證位數,出生日期,初步驗證 52 function cardValidate() { 53 var re = /^[0-9x]{15,18}$/i; 54 if (!re.test(me.ID)) { 55 me.errNum = 7; 56 return false; 57 } 58 if (15 == me.ID.length || 18 == me.ID.length) { 59 var realLen = 0; 60 if (18 == me.ID.length) realLen = 2; 61 var year = parseInt(me.ID.substr(6, 2 + realLen),10); 62 var month = getNum(me.ID.substr(8 + realLen, 2)); 63 var day = parseInt(me.ID.substr(10 + realLen, 2),10); 64 if (4 == year.length) if (year < 1900 || year > 2050) me.errNum = 4; 65 if (month < 1 || month > 12) me.errNum = 5; 66 if (day < 1 || day > 31) me.errNum = 6; 67 return 0 === me.errNum; 68 } else { 69 me.errNum = 3; 70 return false; 71 } 72 } 73 //總和模11應該等於1 74 var aiCheck = function() { 75 var sum = 0; 76 for (var i = 1; i <= me.ID.length; i++) { 77 var ai = me.ID.substr(me.ID.length - i, 1); 78 ai = (ai.toLowerCase() == `x`) ? 10 : ai; 79 var wi = Math.pow(2, i - 1) % 11; 80 sum += parseInt(ai,10) * wi; 81 } 82 return 1 == sum % 11; 83 }; 84 //最後一位校驗,這個可以和aiCheck合在一起,減少一次迴圈 85 var LastByteCheck = function() { 86 var sum = 0; 87 for (var i = 2; i <= me.ID.length; i++) { 88 var ai = me.ID.substr(me.ID.length - i, 1); 89 ai = (ai.toLowerCase() == `x`) ? 10 : ai; 90 var wi = Math.pow(2, i - 1) % 11; 91 sum += parseInt(ai,10) * wi; 92 } 93 var checkCodeIndex = sum % 11; 94 var c = me.ID.substr(me.ID.length - 1, 1); 95 //alert(c+"=="+me.checkCode[checkCodeIndex]); 96 return c == me.checkCode[checkCodeIndex]; 97 }; 98 }