关于身份证的一些处理方法总结
1.身份证前四后三脱敏
/** * 脱敏身份证号,前四后三,中间有多少位就有多少个* */ function formatIdNumber(idNum) { if (typeof idNum !== 'string') { return ''; } if (idNum.length < 7) { return idNum; } let star = '*'.repeat(idNum.length - 7); let value = idNum.slice(0, 4) + star + idNum.slice(idNum.length - 3); return value; } console.log(formatIdNumber('371234201001312016'), '身份证脱敏')
2. 判断身份证是否成年
/* 判断身份是否成年 */ function isAdult(certNo) { // 截取身份证年月日 let certYear = certNo.substr(6, 4); let certMonth = certNo.substr(10, 2); let certDate = certNo.substr(12, 2); // 获取当前年月日 let date = new Date(); let nowYear = date.getFullYear() - 18 + ''; let nowMonth = date.getMonth() + 1 + ''; let nowDate = date.getDate() + ''; if (nowMonth.length == 1) { nowMonth = '0' + nowMonth; } if (nowDate.length == 1) { nowDate = '0' + nowDate; } let cert = certYear + certMonth + certDate; let now = nowYear + nowMonth + nowDate + ''; return now - cert > 0; } console.log(isAdult('371234201001312016'), '身份证')
3. 检验身份证是否合法
/** * @desc 检查字符串是否为合法的身份证号码 * @param {String} id 需要校验的身份证号码 * @return {Boolean} 是否合法身份证号码 * @example testIdNumber('430421197710177894') => false */ function testIdNumber(id) { const AREA_CODE = { 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: "国外" } switch (id.length) { case 15: case 18: { break } default: { return false } } const testInt = id.length == 15 ? id : id.substr(0, 17) /* if (!_.isInteger(Number(testInt))) { //“_.isInteger引用了js库 loadsh 的方法,检验是否为整数” return false } */ const areaCode = parseInt(id.substr(0, 2)) if (!AREA_CODE[areaCode]) { return false } const birthDay = (id.length == 15) ? ("19" + id.substr(6, 6)) : id.substr(6, 8) /* if (!_.isInteger(Number(birthDay))) { return false } */ if (id.length == 18) { const testNumber = (parseInt(id.charAt(0)) + parseInt(id.charAt(10))) * 7 + (parseInt(id.charAt(1)) + parseInt(id .charAt(11))) * 9 + (parseInt(id.charAt(2)) + parseInt(id.charAt(12))) * 10 + (parseInt(id.charAt(3)) + parseInt(id.charAt(13))) * 5 + (parseInt(id.charAt(4)) + parseInt(id.charAt(14))) * 8 + (parseInt(id.charAt( 5)) + parseInt(id.charAt(15))) * 4 + (parseInt(id.charAt(6)) + parseInt(id.charAt(16))) * 2 + parseInt(id .charAt(7)) * 1 + parseInt(id.charAt(8)) * 6 + parseInt(id.charAt(9)) * 3; if (id.charAt(17) != "10X98765432".charAt(testNumber % 11)) { return false } } return true } console.log(testIdNumber('371234201001312016'), '检验身份证是否合法')
注释: lodash 网址:https://www.lodashjs.com/