range.js 2.4 KB

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