range.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import * as util from '../util';
  2. /**
  3. * Rule for validating minimum and maximum allowed values.
  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 range(rule, value, source, errors, options) {
  14. const len = typeof rule.len === 'number';
  15. const min = typeof rule.min === 'number';
  16. const max = typeof rule.max === 'number';
  17. // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
  18. const spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  19. let val = value;
  20. let key = null;
  21. const num = typeof (value) === 'number';
  22. const str = typeof (value) === 'string';
  23. const arr = Array.isArray(value);
  24. if (num) {
  25. key = 'number';
  26. } else if (str) {
  27. key = 'string';
  28. } else if (arr) {
  29. key = 'array';
  30. }
  31. // if the value is not of a supported type for range validation
  32. // the validation rule rule should use the
  33. // type property to also test for a particular type
  34. if (!key) {
  35. return false;
  36. }
  37. if (arr) {
  38. val = value.length;
  39. }
  40. if (str) {
  41. // 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".lenght !== 3
  42. val = value.replace(spRegexp, '_').length;
  43. }
  44. if (len) {
  45. if (val !== rule.len) {
  46. errors.push(util.format(options.messages[key].len, rule.fullField, rule.len));
  47. }
  48. } else if (min && !max && val < rule.min) {
  49. errors.push(util.format(options.messages[key].min, rule.fullField, rule.min));
  50. } else if (max && !min && val > rule.max) {
  51. errors.push(util.format(options.messages[key].max, rule.fullField, rule.max));
  52. } else if (min && max && (val < rule.min || val > rule.max)) {
  53. errors.push(util.format(options.messages[key].range,
  54. rule.fullField, rule.min, rule.max));
  55. }
  56. }
  57. export default range;