猎豆优选小程序

checkIdCard.js 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const city = {
  2. 11: '北京',
  3. 12: '天津',
  4. 13: '河北',
  5. 14: '山西',
  6. 15: '内蒙古',
  7. 21: '辽宁',
  8. 22: '吉林',
  9. 23: '黑龙江 ',
  10. 31: '上海',
  11. 32: '江苏',
  12. 33: '浙江',
  13. 34: '安徽',
  14. 35: '福建',
  15. 36: '江西',
  16. 37: '山东',
  17. 41: '河南',
  18. 42: '湖北 ',
  19. 43: '湖南',
  20. 44: '广东',
  21. 45: '广西',
  22. 46: '海南',
  23. 50: '重庆',
  24. 51: '四川',
  25. 52: '贵州',
  26. 53: '云南',
  27. 54: '西藏 ',
  28. 61: '陕西',
  29. 62: '甘肃',
  30. 63: '青海',
  31. 64: '宁夏',
  32. 65: '新疆',
  33. 71: '台湾',
  34. 81: '香港',
  35. 82: '澳门',
  36. 91: '国外'
  37. };
  38. const regCity = `(${Reflect.ownKeys(city).join('|')})`;
  39. //当前日期
  40. const currentDate = new Date();
  41. const year = String(currentDate.getFullYear()).split('');
  42. const month = String(currentDate.getMonth() + 1).split('');
  43. const day = String(currentDate.getDate()).split('');
  44. //处理小于10的月份和天数
  45. if (month.length < 2) {
  46. month.unshift('0');
  47. }
  48. if (day.length < 2) {
  49. day.unshift('0');
  50. }
  51. //校验时间月、日
  52. const regDay = `(((0[13578]|1[02])([0-2]\\d|3[0-1]))|(02[0-2]\\d)|((0[469]|11)([0-2]\\d|30)))`;
  53. //校验十五位身份证号
  54. const reg15 = `(${regCity}\\d{4}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2})`;
  55. //当前月校验
  56. const currentYearMonth = `${month[0]}${month[1]}${day[0]==0? `0[1-${day[1]}]`:`([0-${day[0]-1}][1-9])|(${day[0]}[0-${day[1]}])`}`;
  57. /***当前年其他月份校验*/
  58. //当前月小于十月份校验
  59. const min10Month = `0[1-${month[1] - 1}](0[1-9]|[1-2]\\d|3[0-1])`;
  60. //当前月大于等于十月份校验
  61. const max10Month = `(0[1-9](0[1-9]|[1-2]\\d|3[0-1]))${month[1]==0? '':`|(1[0-${month[1] - 1}](0[1-9]|[1-2]\\d|3[0-1]))`}`;
  62. const currentYearOtherMonth = month[0] == 0? min10Month:max10Month;
  63. /***组装身份证号校验规则*/
  64. //当前年
  65. const currentYear = `${year[0]}${year[1]}${year[2]}${year[3]}`;
  66. //当前年份校验,当前月份是一月份只使用 currentYearMonth 校验月份
  67. const currentYearReg = `(${currentYear}${ month[0] == 0 && month[1] == 1? '(':`(${currentYearOtherMonth}|`}${currentYearMonth}))`;
  68. //其他年份校验
  69. const regMillenniumMinBirthday = `${year[0]}[0-${year[1]}](([0-${year[2] - 1<0? 0:year[2] - 1}]\\d)|(${year[2]}[0-${year[3] - 1 < 0? 0:year[3] - 1}]))`;
  70. const otherYearReg = `((([0-${year[0] - 1}]\\d{3})|(${regMillenniumMinBirthday}))${regDay})`;
  71. const regBirthday18 = `(${otherYearReg}|${currentYearReg})`;
  72. const reg18 = `(${regCity}\\d{4}${regBirthday18}\\d{3}[0-9Xx])`;
  73. const reg = new RegExp(`^(${reg15}|${reg18})*$`);
  74. const fn = (idCardNum) => {
  75. if (!idCardNum) return false
  76. return reg.test(idCardNum)
  77. }
  78. export default fn