pattern.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  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, rule.fullField, value, rule.pattern));
  22. }
  23. } else if (typeof rule.pattern === 'string') {
  24. var _pattern = new RegExp(rule.pattern);
  25. if (!_pattern.test(value)) {
  26. errors.push(util.format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
  27. }
  28. }
  29. }
  30. }
  31. export default pattern;