You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

validators.py 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from django.core.exceptions import ValidationError
  2. from django.core.validators import (
  3. MaxLengthValidator, MaxValueValidator, MinLengthValidator,
  4. MinValueValidator,
  5. )
  6. from django.utils.deconstruct import deconstructible
  7. from django.utils.translation import gettext_lazy as _, ngettext_lazy
  8. class ArrayMaxLengthValidator(MaxLengthValidator):
  9. message = ngettext_lazy(
  10. 'List contains %(show_value)d item, it should contain no more than %(limit_value)d.',
  11. 'List contains %(show_value)d items, it should contain no more than %(limit_value)d.',
  12. 'limit_value')
  13. class ArrayMinLengthValidator(MinLengthValidator):
  14. message = ngettext_lazy(
  15. 'List contains %(show_value)d item, it should contain no fewer than %(limit_value)d.',
  16. 'List contains %(show_value)d items, it should contain no fewer than %(limit_value)d.',
  17. 'limit_value')
  18. @deconstructible
  19. class KeysValidator:
  20. """A validator designed for HStore to require/restrict keys."""
  21. messages = {
  22. 'missing_keys': _('Some keys were missing: %(keys)s'),
  23. 'extra_keys': _('Some unknown keys were provided: %(keys)s'),
  24. }
  25. strict = False
  26. def __init__(self, keys, strict=False, messages=None):
  27. self.keys = set(keys)
  28. self.strict = strict
  29. if messages is not None:
  30. self.messages = {**self.messages, **messages}
  31. def __call__(self, value):
  32. keys = set(value)
  33. missing_keys = self.keys - keys
  34. if missing_keys:
  35. raise ValidationError(
  36. self.messages['missing_keys'],
  37. code='missing_keys',
  38. params={'keys': ', '.join(missing_keys)},
  39. )
  40. if self.strict:
  41. extra_keys = keys - self.keys
  42. if extra_keys:
  43. raise ValidationError(
  44. self.messages['extra_keys'],
  45. code='extra_keys',
  46. params={'keys': ', '.join(extra_keys)},
  47. )
  48. def __eq__(self, other):
  49. return (
  50. isinstance(other, self.__class__) and
  51. self.keys == other.keys and
  52. self.messages == other.messages and
  53. self.strict == other.strict
  54. )
  55. class RangeMaxValueValidator(MaxValueValidator):
  56. def compare(self, a, b):
  57. return a.upper is None or a.upper > b
  58. message = _('Ensure that this range is completely less than or equal to %(limit_value)s.')
  59. class RangeMinValueValidator(MinValueValidator):
  60. def compare(self, a, b):
  61. return a.lower is None or a.lower < b
  62. message = _('Ensure that this range is completely greater than or equal to %(limit_value)s.')