range.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _util = require('../util');
  6. var util = _interopRequireWildcard(_util);
  7. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
  8. /**
  9. * Rule for validating minimum and maximum allowed values.
  10. *
  11. * @param rule The validation rule.
  12. * @param value The value of the field on the source object.
  13. * @param source The source object being validated.
  14. * @param errors An array of errors that this rule may add
  15. * validation errors to.
  16. * @param options The validation options.
  17. * @param options.messages The validation messages.
  18. */
  19. function range(rule, value, source, errors, options) {
  20. var len = typeof rule.len === 'number';
  21. var min = typeof rule.min === 'number';
  22. var max = typeof rule.max === 'number';
  23. // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
  24. var spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  25. var val = value;
  26. var key = null;
  27. var num = typeof value === 'number';
  28. var str = typeof value === 'string';
  29. var arr = Array.isArray(value);
  30. if (num) {
  31. key = 'number';
  32. } else if (str) {
  33. key = 'string';
  34. } else if (arr) {
  35. key = 'array';
  36. }
  37. // if the value is not of a supported type for range validation
  38. // the validation rule rule should use the
  39. // type property to also test for a particular type
  40. if (!key) {
  41. return false;
  42. }
  43. if (arr) {
  44. val = value.length;
  45. }
  46. if (str) {
  47. // 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".lenght !== 3
  48. val = value.replace(spRegexp, '_').length;
  49. }
  50. if (len) {
  51. if (val !== rule.len) {
  52. errors.push(util.format(options.messages[key].len, rule.fullField, rule.len));
  53. }
  54. } else if (min && !max && val < rule.min) {
  55. errors.push(util.format(options.messages[key].min, rule.fullField, rule.min));
  56. } else if (max && !min && val > rule.max) {
  57. errors.push(util.format(options.messages[key].max, rule.fullField, rule.max));
  58. } else if (min && max && (val < rule.min || val > rule.max)) {
  59. errors.push(util.format(options.messages[key].range, rule.fullField, rule.min, rule.max));
  60. }
  61. }
  62. exports['default'] = range;
  63. module.exports = exports['default'];