pattern.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import * as util from '../util';
  2. /**
  3. * Rule for validating a regular expression pattern.
  4. *
  5. * @param rule The validation rule.
  6. * @param value The value of the field on the source object.
  7. * @param source The source object being validated.
  8. * @param errors An array of errors that this rule may add
  9. * validation errors to.
  10. * @param options The validation options.
  11. * @param options.messages The validation messages.
  12. */
  13. function pattern(rule, value, source, errors, options) {
  14. if (rule.pattern) {
  15. if (rule.pattern instanceof RegExp) {
  16. // if a RegExp instance is passed, reset `lastIndex` in case its `global`
  17. // flag is accidentally set to `true`, which in a validation scenario
  18. // is not necessary and the result might be misleading
  19. rule.pattern.lastIndex = 0;
  20. if (!rule.pattern.test(value)) {
  21. errors.push(util.format(options.messages.pattern.mismatch,
  22. rule.fullField, value, rule.pattern));
  23. }
  24. } else if (typeof rule.pattern === 'string') {
  25. const _pattern = new RegExp(rule.pattern.replace(/^\/|\/$/g,''));
  26. if (!_pattern.test(value)) {
  27. errors.push(util.format(options.messages.pattern.mismatch,
  28. rule.fullField, value, rule.pattern));
  29. }
  30. }
  31. }
  32. }
  33. export default pattern;