pattern.js 1.6 KB

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