common.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // 身份证号码验证
  2. function identityCodeValid(code) {
  3. var city = {
  4. 11: "北京",
  5. 12: "天津",
  6. 13: "河北",
  7. 14: "山西",
  8. 15: "内蒙古",
  9. 21: "辽宁",
  10. 22: "吉林",
  11. 23: "黑龙江 ",
  12. 31: "上海",
  13. 32: "江苏",
  14. 33: "浙江",
  15. 34: "安徽",
  16. 35: "福建",
  17. 36: "江西",
  18. 37: "山东",
  19. 41: "河南",
  20. 42: "湖北 ",
  21. 43: "湖南",
  22. 44: "广东",
  23. 45: "广西",
  24. 46: "海南",
  25. 50: "重庆",
  26. 51: "四川",
  27. 52: "贵州",
  28. 53: "云南",
  29. 54: "西藏 ",
  30. 61: "陕西",
  31. 62: "甘肃",
  32. 63: "青海",
  33. 64: "宁夏",
  34. 65: "新疆",
  35. 71: "台湾",
  36. 81: "香港",
  37. 82: "澳门",
  38. 91: "国外 "
  39. };
  40. var tip = "";
  41. var pass = true;
  42. if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
  43. tip = "身份证号格式错误";
  44. pass = false;
  45. } else if (!city[code.substr(0, 2)]) {
  46. tip = "地址编码错误";
  47. pass = false;
  48. } else {
  49. //18位身份证需要验证最后一位校验位
  50. if (code.length == 18) {
  51. code = code.split('');
  52. //∑(ai×Wi)(mod 11)
  53. //加权因子
  54. var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  55. //校验位
  56. var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
  57. var sum = 0;
  58. var ai = 0;
  59. var wi = 0;
  60. for (var i = 0; i < 17; i++) {
  61. ai = code[i];
  62. wi = factor[i];
  63. sum += ai * wi;
  64. }
  65. var last = parity[sum % 11];
  66. if (parity[sum % 11] != code[17]) {
  67. tip = "校验位错误";
  68. pass = false;
  69. }
  70. }
  71. }
  72. return pass;
  73. }
  74. module.exports.identityCodeValid = identityCodeValid; //判断身份证号