转的,比较完善的验证身份证号的代码

 /*
check(ID)验证身份证号码
返回值:0 : "是正确的身份证号"
1 : "身份证校验不符合求和模11=1这个等式",
2 : "身份证最后一位校验位有误",
3 : "身份证位数不正确",
4 : "年份错误",
5 : "月份错误",
6 : "日错误" */ function check(ID) {
var ck = new IDCard();
ck.check(ID);
return ck.errNum;
} function IDCard(ID) {
var me = this;
this.checkCode = new Array(1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2);
this.ID;
this.errNum = 0;
this.err = {
1 : "身份证校验不符合求和模11=1这个等式",
2 : "身份证最后一位校验位有误",
3 : "身份证位数不正确",
4 : "年份错误",
5 : "月份错误",
6 : "日错误"
};
this.err_msg = function() {
return (0 !== this.errNum) ? this.err[this.errNum] : null;
};
this.check = function(ID) {
this.errNum = 0;
this.ID = ID;
if (cardValidate()) {
if (!aiCheck()) this.errNum = 1;
if (!LastByteCheck()) this.errNum = 2;
return (0 === this.errNum) ? true: false;
} else {
return false;
}
};
function getNum(str) {
var re = /^[0]*([0-9]*)$/;
str.match(re);
return parseInt(RegExp.$1,10);
}
//对身份证位数,出生日期,初步验证
function cardValidate() {
var re = /^[0-9x]{15,18}$/i;
if (!re.test(me.ID)) {
me.errNum = 7;
return false;
}
if (15 == me.ID.length || 18 == me.ID.length) {
var realLen = 0;
if (18 == me.ID.length) realLen = 2;
var year = parseInt(me.ID.substr(6, 2 + realLen),10);
var month = getNum(me.ID.substr(8 + realLen, 2));
var day = parseInt(me.ID.substr(10 + realLen, 2),10);
if (4 == year.length) if (year < 1900 || year > 2050) me.errNum = 4;
if (month < 1 || month > 12) me.errNum = 5;
if (day < 1 || day > 31) me.errNum = 6;
return 0 === me.errNum;
} else {
me.errNum = 3;
return false;
}
}
//总和模11应该等于1
var aiCheck = function() {
var sum = 0;
for (var i = 1; i <= me.ID.length; i++) {
var ai = me.ID.substr(me.ID.length - i, 1);
ai = (ai.toLowerCase() == 'x') ? 10 : ai;
var wi = Math.pow(2, i - 1) % 11;
sum += parseInt(ai,10) * wi;
}
return 1 == sum % 11;
};
//最后一位校验,这个可以和aiCheck合在一起,减少一次循环
var LastByteCheck = function() {
var sum = 0;
for (var i = 2; i <= me.ID.length; i++) {
var ai = me.ID.substr(me.ID.length - i, 1);
ai = (ai.toLowerCase() == 'x') ? 10 : ai;
var wi = Math.pow(2, i - 1) % 11;
sum += parseInt(ai,10) * wi;
}
var checkCodeIndex = sum % 11;
var c = me.ID.substr(me.ID.length - 1, 1);
//alert(c+"=="+me.checkCode[checkCodeIndex]);
return c == me.checkCode[checkCodeIndex];
};
}
05-04 08:37