Source: regexp.js

  1. /*
  2. 正则匹配
  3. Thanks:https://github.com/talyssonoc/CommonRegexJS/blob/master/lib/commonregex.js
  4. */
  5. /**
  6. * [regularExpressionTest description] 函数防抖动
  7. * @param type {String} 验证类型
  8. * @param val {String/Number} 进行验证的值
  9. * @return {Boolean} 返回验证结果
  10. */
  11. function regularExpressionTest(type, val) {
  12. var testRule;
  13. switch (type) {
  14. case 'positive_integers':
  15. testRule = /^[0-9]*[1-9][0-9]*$/; //正整数
  16. break;
  17. case 'positive_integers_zero':
  18. testRule = /^[0-9]*[0-9][0-9]*$/; //正整数(包括0)
  19. break;
  20. case 'positive_floating_zero':
  21. testRule = /^\d+(\.\d+)?$/; //非负浮点数(包括0)
  22. break;
  23. case 'positive_integers_zero_two_decimal':
  24. testRule = /^\d+(\.\d{1,2})?$/; //非负数(小数点后最多有两位,包括0)
  25. break;
  26. case 'phone':
  27. testRule = /^1[35847][0-9][0-9]{8}$/; //手机号
  28. break;
  29. case 'telephone':
  30. testRule = /^([0-9]{3,4}-)?[0-9]{7,8}$/; //固话号
  31. break;
  32. case 'email':
  33. testRule = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+(([.-])[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/; //邮箱
  34. break;
  35. case 'time':
  36. testRule = /\b((0?[0-9]|1[0-2])(:[0-5][0-9])?(am|pm)|([01]?[0-9]|2[0-3]):[0-5][0-9])/gim; //时间
  37. break;
  38. case 'link':
  39. testRule = /((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?\xab\xbb\u201c\u201d\u2018\u2019]))/gim; // 链接
  40. break;
  41. case 'IPv4':
  42. testRule = /\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/gm; // IPv4地址
  43. break;
  44. case 'IPv6':
  45. testRule = /((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))\b/gim; //IPv6地址
  46. break;
  47. case 'hexColor':
  48. testRule = /#(?:[0-9a-fA-F]{3}){1,2}\b/gim; // 十六进制颜色像素值
  49. break;
  50. case 'creditCard':
  51. testRule = /((?:(?:\d{4}[- ]){3}\d{4}|\d{16}))(?![\d])/gm; //信用卡账号
  52. break;
  53. }
  54. return testRule.test(val);
  55. }