verify.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var phoneNum = /^1[0-9]{10}$/
  2. var number = /^[0-9]*$/
  3. function isPhoneNum(target) {
  4. return phoneNum.test(target)
  5. }
  6. function isNumber(target) {
  7. return number.test(target)
  8. }
  9. function isIdentityCard(code) {
  10. var city = { 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: "国外 " };
  11. var pass = true;
  12. 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)) {
  13. return false
  14. } else if (!city[code.substr(0, 2)]) {
  15. return false;
  16. } else {
  17. //18位身份证需要验证最后一位校验位
  18. if (code.length == 18) {
  19. code = code.split('');
  20. //∑(ai×Wi)(mod 11)
  21. //加权因子
  22. var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  23. //校验位
  24. var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
  25. var sum = 0;
  26. var ai = 0;
  27. var wi = 0;
  28. for (var i = 0; i < 17; i++) {
  29. ai = code[i];
  30. wi = factor[i];
  31. sum += ai * wi;
  32. }
  33. var last = parity[sum % 11];
  34. if (parity[sum % 11] != code[17]) {
  35. return false;
  36. }
  37. }
  38. }
  39. return true;
  40. }
  41. function getIdentityCardAge(code) {
  42. var err = 0
  43. var nowY = new Date().format('yyyy')
  44. var borY = String(code).slice(6, 10)
  45. var now = new Date().format('yyyyMMdd')
  46. var bri = nowY + String(code).slice(10, 14)
  47. if (Number(now) < Number(bri)) {
  48. err = -1
  49. }
  50. return Number(nowY) - Number(borY) + err
  51. }
  52. function getIdentityCardGender(code) {
  53. var num = String(code).slice(16, 17)
  54. return Number(num) % 2 == 0 ? 0 : 1
  55. }
  56. module.exports = {
  57. isIdentityCard: isIdentityCard,
  58. isPhoneNum: isPhoneNum,
  59. isNumber: isNumber,
  60. getIdentityCardAge: getIdentityCardAge,
  61. getIdentityCardGender: getIdentityCardGender,
  62. }