转的,比较完善的验证身份证号的代码
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 }