test.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. 'use strict';
  2. function idCodeValid(code) {
  3. // 身份证号合法性验证
  4. // 支持15位和18位身份证号
  5. // 支持地址编码、出生日期、校验位验证
  6. const city = {
  7. 11: '北京',
  8. 12: '天津',
  9. 13: '河北',
  10. 14: '山西',
  11. 15: '内蒙古',
  12. 21: '辽宁',
  13. 22: '吉林',
  14. 23: '黑龙江 ',
  15. 31: '上海',
  16. 32: '江苏',
  17. 33: '浙江',
  18. 34: '安徽',
  19. 35: '福建',
  20. 36: '江西',
  21. 37: '山东',
  22. 41: '河南',
  23. 42: '湖北 ',
  24. 43: '湖南',
  25. 44: '广东',
  26. 45: '广西',
  27. 46: '海南',
  28. 50: '重庆',
  29. 51: '四川',
  30. 52: '贵州',
  31. 53: '云南',
  32. 54: '西藏 ',
  33. 61: '陕西',
  34. 62: '甘肃',
  35. 63: '青海',
  36. 64: '宁夏',
  37. 65: '新疆',
  38. 71: '台湾',
  39. 81: '香港',
  40. 82: '澳门',
  41. 91: '国外 ',
  42. };
  43. let row = {
  44. pass: true,
  45. msg: '验证成功',
  46. };
  47. if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
  48. row = {
  49. pass: false,
  50. msg: '身份证号格式错误',
  51. };
  52. } else if (!city[code.substr(0, 2)]) {
  53. row = {
  54. pass: false,
  55. msg: '身份证号地址编码错误',
  56. };
  57. } else {
  58. // 18位身份证需要验证最后一位校验位
  59. if (code.length === 18) {
  60. code = code.split('');
  61. // ∑(ai×Wi)(mod 11)
  62. // 加权因子
  63. const factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
  64. // 校验位
  65. const parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
  66. let sum = 0;
  67. let ai = 0;
  68. let wi = 0;
  69. for (let i = 0; i < 17; i++) {
  70. ai = code[i];
  71. wi = factor[i];
  72. sum += ai * wi;
  73. }
  74. if (parity[sum % 11] !== code[17].toUpperCase()) {
  75. row = {
  76. pass: false,
  77. msg: '身份证号校验位错误',
  78. should: parity[sum % 11],
  79. is: code[17].toUpperCase(),
  80. };
  81. }
  82. }
  83. }
  84. return row;
  85. }
  86. const arr = [
  87. '22010319950601161X',
  88. '220103199506119700',
  89. '220104199506196198',
  90. '220104199506086490',
  91. '220104199506039600',
  92. '220104199506280349',
  93. '220104199506036581',
  94. '220104199506154414',
  95. '220104199506040919',
  96. '220104199506269852',
  97. '220104199506039598',
  98. ];
  99. for (const i of arr) {
  100. const res = idCodeValid(i);
  101. console.log(`${i}:${JSON.stringify(res)}`);
  102. }