range.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. var val = value;
  18. var key = null;
  19. var num = typeof value === 'number';
  20. var str = typeof value === 'string';
  21. var arr = Array.isArray(value);
  22. if (num) {
  23. key = 'number';
  24. } else if (str) {
  25. key = 'string';
  26. } else if (arr) {
  27. key = 'array';
  28. }
  29. // if the value is not of a supported type for range validation
  30. // the validation rule rule should use the
  31. // type property to also test for a particular type
  32. if (!key) {
  33. return false;
  34. }
  35. if (str || arr) {
  36. val = value.length;
  37. }
  38. if (len) {
  39. if (val !== rule.len) {
  40. errors.push(util.format(options.messages[key].len, rule.fullField, rule.len));
  41. }
  42. } else if (min && !max && val < rule.min) {
  43. errors.push(util.format(options.messages[key].min, rule.fullField, rule.min));
  44. } else if (max && !min && val > rule.max) {
  45. errors.push(util.format(options.messages[key].max, rule.fullField, rule.max));
  46. } else if (min && max && (val < rule.min || val > rule.max)) {
  47. errors.push(util.format(options.messages[key].range, rule.fullField, rule.min, rule.max));
  48. }
  49. }
  50. export default range;