range.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _util = require("../util");
  7. var range = function range(rule, value, source, errors, options) {
  8. var len = typeof rule.len === 'number';
  9. var min = typeof rule.min === 'number';
  10. var max = typeof rule.max === 'number';
  11. // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
  12. var spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  13. var val = value;
  14. var key = null;
  15. var num = typeof value === 'number';
  16. var str = typeof value === 'string';
  17. var arr = Array.isArray(value);
  18. if (num) {
  19. key = 'number';
  20. } else if (str) {
  21. key = 'string';
  22. } else if (arr) {
  23. key = 'array';
  24. }
  25. // if the value is not of a supported type for range validation
  26. // the validation rule rule should use the
  27. // type property to also test for a particular type
  28. if (!key) {
  29. return false;
  30. }
  31. if (arr) {
  32. val = value.length;
  33. }
  34. if (str) {
  35. // 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".length !== 3
  36. val = value.replace(spRegexp, '_').length;
  37. }
  38. if (len) {
  39. if (val !== rule.len) {
  40. errors.push((0, _util.format)(options.messages[key].len, rule.fullField, rule.len));
  41. }
  42. } else if (min && !max && val < rule.min) {
  43. errors.push((0, _util.format)(options.messages[key].min, rule.fullField, rule.min));
  44. } else if (max && !min && val > rule.max) {
  45. errors.push((0, _util.format)(options.messages[key].max, rule.fullField, rule.max));
  46. } else if (min && max && (val < rule.min || val > rule.max)) {
  47. errors.push((0, _util.format)(options.messages[key].range, rule.fullField, rule.min, rule.max));
  48. }
  49. };
  50. var _default = exports.default = range;