做判断的时候总会遇到要效验身份证号码正不正确的问题,所有特地百度搜搜,整理,能实现身份证号长度校验、身份证号地址编码校验、身份证号中的年月日并校验
/* * cardRequired.js * 身份证号校验&&必填 * val value * 身份证号合法性验证 支持15位和18位身份证号 //支持地址编码、出生日期、校验位验证 * Y J * */ var cardRequired =function(val) { var b = "", c = "", d = {}; /*身份证号长度校验*/ if(!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(val)) { return { is: false, tip: "你输入的身份证长度或格式错误!" } }; /*身份证号地址编码校验*/ if(!/^11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65|71|81|82|91$/.test(val.substr(0, 2))) { return { is: false, tip: "你输入的身份证号地址编码错误!" } }; /*15位身份证号转18位身份证号*/ var a18 = val; if(val.length == ‘15‘) { var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); var arrCh = new Array(‘1‘, ‘0‘, ‘X‘, ‘9‘, ‘8‘, ‘7‘, ‘6‘, ‘5‘, ‘4‘, ‘3‘, ‘2‘); var cardTemp = 0, i; a18 = "" a18 = val.substr(0, 6) + ‘19‘ + val.substr(6, val.length - 6); for(i = 0; i < 17; i++) { cardTemp += a18.substr(i, 1) * arrInt[i]; } a18 += arrCh[cardTemp % 11]; } /*获取身份证号中的年月日并校验*/ var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X|x)$/; var arr_data = a18.match(re_eighteen); var year = arr_data[2]; var month = arr_data[3]; var day = arr_data[4]; var birthday = new Date(year + ‘/‘ + month + ‘/‘ + day); var now = new Date(); var time = now.getFullYear() - year; /*校验年月日是否合理 */ if(birthday.getFullYear() == year && (birthday.getMonth() + 1) == month && birthday.getDate() == day) { if(time >= 0 || time <= 130) { return { is: "true", tip: "" } } }; return { is: false, tip: "你输入的身份证号出生年月日不合理!" } }