validator.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // 地区码对照表
  2. const cityCodes = {
  3. 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
  4. 21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
  5. 33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",
  6. 41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",
  7. 46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",
  8. 54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",
  9. 65:"新疆",71:"台湾",81:"香港",82:"澳门"
  10. };
  11. // 加权因子
  12. const factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
  13. // 校验位对应值
  14. const parity = [1,0,'X',9,8,7,6,5,4,3,2];
  15. function validateIDCard(id) {
  16. // 基础格式校验
  17. if(!/^\d{17}[\dXx]$/.test(id)) return false;
  18. // 校验地区码
  19. if(!cityCodes[id.substr(0,2)]) return false;
  20. // 校验生日
  21. const birthDate = id.substr(6,8);
  22. const year = birthDate.substr(0,4);
  23. const month = birthDate.substr(4,2);
  24. const day = birthDate.substr(6,2);
  25. const date = new Date(year, month-1, day);
  26. if(date.getFullYear() != year ||
  27. (date.getMonth()+1) != month ||
  28. date.getDate() != day) {
  29. return false;
  30. }
  31. // 校验码校验
  32. let sum = 0;
  33. for(let i=0; i<17; i++) {
  34. sum += parseInt(id.charAt(i)) * factor[i];
  35. }
  36. const lastChar = id.charAt(17).toUpperCase();
  37. return parity[sum%11] == lastChar;
  38. }
  39. /***************校验手机号***************/
  40. function validatePhone(phone) {
  41. return /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/.test(phone);
  42. }
  43. /***************校验出生日期与身份证号是否一致***************/
  44. function getBirthFromID(id) {
  45. if(id.length === 18) {
  46. return id.substr(6,4) + '-' + id.substr(10,2) + '-' + id.substr(12,2);
  47. } else if(id.length === 15) {
  48. return '19' + id.substr(6,2) + '-' + id.substr(8,2) + '-' + id.substr(10,2);
  49. }
  50. return null;
  51. }
  52. function validateDate(dateStr) {
  53. const date = new Date(dateStr.replace(/-/g, '/'));
  54. return !isNaN(date.getTime());
  55. }
  56. function checkBirthMatch(idCard, inputDate) {
  57. const idBirth = getBirthFromID(idCard); console.log("idBirth="+idBirth) ;
  58. if(!idBirth || !validateDate(idBirth)) return false;
  59. // 标准化日期格式比较
  60. /*const formatDate = (d) => new Date(d).toISOString().split('T');
  61. console.log("idBirth1="+formatDate(idBirth)) ;
  62. console.log("idBirth2="+formatDate(inputDate)) ;
  63. return formatDate(idBirth) === formatDate(inputDate);*/
  64. return idBirth === inputDate;
  65. }
  66. /*********************校验车牌************************/
  67. function validatePlate(plateNumber) {
  68. const regularPlate = /^[\u4e00-\u9fa5][A-NP-Z][A-NP-Z0-9]{5}$/; //普通车牌
  69. const newEnergyPlate = /^[\u4e00-\u9fa5][A-NP-Z]D[A-NP-Z0-9]{6}$/; //新能源车牌
  70. return regularPlate.test(plateNumber) || newEnergyPlate.test(plateNumber);
  71. }