validator-extras.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. const _ = require("lodash");
  3. const validator = _.cloneDeep(require("validator"));
  4. const moment = require("moment");
  5. const extensions = {
  6. extend(name, fn) {
  7. this[name] = fn;
  8. return this;
  9. },
  10. notEmpty(str) {
  11. return !str.match(/^[\s\t\r\n]*$/);
  12. },
  13. len(str, min, max) {
  14. return this.isLength(str, min, max);
  15. },
  16. isUrl(str) {
  17. return this.isURL(str);
  18. },
  19. isIPv6(str) {
  20. return this.isIP(str, 6);
  21. },
  22. isIPv4(str) {
  23. return this.isIP(str, 4);
  24. },
  25. notIn(str, values) {
  26. return !this.isIn(str, values);
  27. },
  28. regex(str, pattern, modifiers) {
  29. str += "";
  30. if (Object.prototype.toString.call(pattern).slice(8, -1) !== "RegExp") {
  31. pattern = new RegExp(pattern, modifiers);
  32. }
  33. return str.match(pattern);
  34. },
  35. notRegex(str, pattern, modifiers) {
  36. return !this.regex(str, pattern, modifiers);
  37. },
  38. isDecimal(str) {
  39. return str !== "" && !!str.match(/^(?:-?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][+-]?(?:[0-9]+))?$/);
  40. },
  41. min(str, val) {
  42. const number = parseFloat(str);
  43. return isNaN(number) || number >= val;
  44. },
  45. max(str, val) {
  46. const number = parseFloat(str);
  47. return isNaN(number) || number <= val;
  48. },
  49. not(str, pattern, modifiers) {
  50. return this.notRegex(str, pattern, modifiers);
  51. },
  52. contains(str, elem) {
  53. return !!elem && str.includes(elem);
  54. },
  55. notContains(str, elem) {
  56. return !this.contains(str, elem);
  57. },
  58. is(str, pattern, modifiers) {
  59. return this.regex(str, pattern, modifiers);
  60. }
  61. };
  62. exports.extensions = extensions;
  63. validator.isImmutable = function(value, validatorArgs, field, modelInstance) {
  64. return modelInstance.isNewRecord || modelInstance.dataValues[field] === modelInstance._previousDataValues[field];
  65. };
  66. validator.notNull = function(val) {
  67. return val !== null && val !== void 0;
  68. };
  69. _.forEach(extensions, (extend, key) => {
  70. validator[key] = extend;
  71. });
  72. validator.isNull = validator.isEmpty;
  73. validator.isDate = function(dateString) {
  74. const parsed = Date.parse(dateString);
  75. if (isNaN(parsed)) {
  76. return false;
  77. }
  78. const date = new Date(parsed);
  79. return moment(date.toISOString()).isValid();
  80. };
  81. exports.validator = validator;
  82. //# sourceMappingURL=validator-extras.js.map