pattern.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict';
  2. exports.__esModule = true;
  3. var _util = require('../util');
  4. var util = _interopRequireWildcard(_util);
  5. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
  6. /**
  7. * Rule for validating a regular expression pattern.
  8. *
  9. * @param rule The validation rule.
  10. * @param value The value of the field on the source object.
  11. * @param source The source object being validated.
  12. * @param errors An array of errors that this rule may add
  13. * validation errors to.
  14. * @param options The validation options.
  15. * @param options.messages The validation messages.
  16. */
  17. function pattern(rule, value, source, errors, options) {
  18. if (rule.pattern) {
  19. if (rule.pattern instanceof RegExp) {
  20. // if a RegExp instance is passed, reset `lastIndex` in case its `global`
  21. // flag is accidentally set to `true`, which in a validation scenario
  22. // is not necessary and the result might be misleading
  23. rule.pattern.lastIndex = 0;
  24. if (!rule.pattern.test(value)) {
  25. errors.push(util.format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
  26. }
  27. } else if (typeof rule.pattern === 'string') {
  28. var _pattern = new RegExp(rule.pattern);
  29. if (!_pattern.test(value)) {
  30. errors.push(util.format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
  31. }
  32. }
  33. }
  34. }
  35. exports['default'] = pattern;
  36. module.exports = exports['default'];