range.js 1.6 KB

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