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.
 
 
 
 

79 lines
2.7 KiB

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