range.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. var len = typeof rule.len === 'number';
  15. var min = typeof rule.min === 'number';
  16. var max = typeof rule.max === 'number';
  17. // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
  18. var spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  19. var val = value;
  20. var key = null;
  21. var num = typeof value === 'number';
  22. var str = typeof value === 'string';
  23. var 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, rule.fullField, rule.min, rule.max));
  54. }
  55. }
  56. export default range;