regexp-validator.js 904 B

123456789101112131415161718192021222324252627282930
  1. import {stringToRegexp} from '../../../../../utils/index.js';
  2. import {InvalidArgumentError} from '../../../../../errors/index.js';
  3. /**
  4. * Regexp validator.
  5. *
  6. * @param {*} value
  7. * @param {string|RegExp|boolean} options
  8. * @param {object} context
  9. * @returns {boolean}
  10. */
  11. export function regexpValidator(value, options, context) {
  12. if (options === false) return true;
  13. if (typeof options !== 'string' && !(options instanceof RegExp))
  14. throw new InvalidArgumentError(
  15. 'The validator %v requires the "options" argument ' +
  16. 'as a String or RegExp, but %v given.',
  17. context.validatorName,
  18. options,
  19. );
  20. if (typeof value === 'string') {
  21. const regexp = stringToRegexp(options);
  22. return regexp.test(value);
  23. }
  24. throw new InvalidArgumentError(
  25. 'The property validator %v requires ' + 'a String value, but %v given.',
  26. context.validatorName,
  27. value,
  28. );
  29. }