如题,分享自用的判断身份证是否合法的Javascript函数(从网上找到并稍作修改),返回一个JsonObject,如何不符合规则,返回isTrue=false;如何合法,就返回
{ isTrue: true, year: 1989, month: 11, day: 23, isMale: true, isFemale: false, }
得到出生年月日,性别等信息。
硬货代码
// 测试: console.log(validateIdNo('410106198911230197')); console.log(validateIdNo('370612198405097786')); console.log(validateIdNo('370612198405097711')); //测试不合法的身份证号码 /** * 检查给定的身份证号码是否符合规则 * @return info: * { * isTrue: false, //是否合法,以下都是基于isTrue是true合法的情况下 * year: null, //出生年份 * month: null, //出生月份 * day: null, //出生日 * isMale: false, //是否是男性 * isFemale: false, //是否是女性 * }; **/ function validateIdNo(idNo) { var info = { isTrue: false, year: null, month: null, day: null, isMale: false, isFemale: false, }; if (!idNo || (15 != idNo.length && 18 != idNo.length)) { info.isTrue = false; return info; } if (15 == idNo.length) { var year = idNo.substring(6, 8); var month = idNo.substring(8, 10); var day = idNo.substring(10, 12); var p = idNo.substring(14, 15); //性别位 var birthday = new Date(year, parseFloat(month) - 1, parseFloat(day)); // 对于老身份证中的年龄则不需考虑千年虫问题而使用getYear()方法 if ( birthday.getYear() != parseFloat(year) || birthday.getMonth() != parseFloat(month) - 1 || birthday.getDate() != parseFloat(day) ) { info.isTrue = false; } else { info.isTrue = true; info.year = birthday.getFullYear(); info.month = birthday.getMonth() + 1; info.day = birthday.getDate(); if (p % 2 == 0) { info.isFemale = true; info.isMale = false; } else { info.isFemale = false; info.isMale = true; } } return info; } if (18 == idNo.length) { var year = idNo.substring(6, 10); var month = idNo.substring(10, 12); var day = idNo.substring(12, 14); var p = idNo.substring(14, 17); var birthday = new Date(year, parseFloat(month) - 1, parseFloat(day)); // 这里用getFullYear()获取年份,避免千年虫问题 if ( birthday.getFullYear() != parseFloat(year) || birthday.getMonth() != parseFloat(month) - 1 || birthday.getDate() != parseFloat(day) ) { info.isTrue = false; return info; } var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]; // 加权因子 var Y = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; // 身份证验证位值.10代表X // 验证校验位 var sum = 0; // 声明加权求和变量 var _idNo = idNo.split(""); if (_idNo[17].toLowerCase() == "x") { _idNo[17] = 10; // 将最后位为x的验证码替换为10方便后续操作 } for (var i = 0; i < 17; i++) { sum += Wi[i] * _idNo[i]; // 加权求和 } var i = sum % 11; // 得到验证码所位置 if (_idNo[17] != Y[i]) { info.isTrue = false; return info; } info.isTrue = true; info.year = birthday.getFullYear(); info.month = birthday.getMonth() + 1; info.day = birthday.getDate(); if (p % 2 == 0) { info.isFemale = true; info.isMale = false; } else { info.isFemale = false; info.isMale = true; } return info; } return info; }
文章评论