validators.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. from __future__ import unicode_literals
  2. import re
  3. from django.core.exceptions import ValidationError
  4. from django.utils.deconstruct import deconstructible
  5. from django.utils.translation import ugettext_lazy as _, ungettext_lazy
  6. from django.utils.encoding import force_text
  7. from django.utils.ipv6 import is_valid_ipv6_address
  8. from django.utils import six
  9. from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
  10. # These values, if given to validate(), will trigger the self.required check.
  11. EMPTY_VALUES = (None, '', [], (), {})
  12. @deconstructible
  13. class RegexValidator(object):
  14. regex = ''
  15. message = _('Enter a valid value.')
  16. code = 'invalid'
  17. inverse_match = False
  18. flags = 0
  19. def __init__(self, regex=None, message=None, code=None, inverse_match=None, flags=None):
  20. if regex is not None:
  21. self.regex = regex
  22. if message is not None:
  23. self.message = message
  24. if code is not None:
  25. self.code = code
  26. if inverse_match is not None:
  27. self.inverse_match = inverse_match
  28. if flags is not None:
  29. self.flags = flags
  30. if self.flags and not isinstance(self.regex, six.string_types):
  31. raise TypeError("If the flags are set, regex must be a regular expression string.")
  32. # Compile the regex if it was not passed pre-compiled.
  33. if isinstance(self.regex, six.string_types):
  34. self.regex = re.compile(self.regex, self.flags)
  35. def __call__(self, value):
  36. """
  37. Validates that the input matches the regular expression
  38. if inverse_match is False, otherwise raises ValidationError.
  39. """
  40. if not (self.inverse_match is not bool(self.regex.search(
  41. force_text(value)))):
  42. raise ValidationError(self.message, code=self.code)
  43. def __eq__(self, other):
  44. return (
  45. isinstance(other, RegexValidator) and
  46. self.regex.pattern == other.regex.pattern and
  47. self.regex.flags == other.regex.flags and
  48. (self.message == other.message) and
  49. (self.code == other.code) and
  50. (self.inverse_match == other.inverse_match)
  51. )
  52. def __ne__(self, other):
  53. return not (self == other)
  54. @deconstructible
  55. class URLValidator(RegexValidator):
  56. regex = re.compile(
  57. r'^(?:[a-z0-9\.\-]*)://' # scheme is validated separately
  58. r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)|' # domain...
  59. r'localhost|' # localhost...
  60. r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
  61. r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
  62. r'(?::\d+)?' # optional port
  63. r'(?:/?|[/?]\S+)$', re.IGNORECASE)
  64. message = _('Enter a valid URL.')
  65. schemes = ['http', 'https', 'ftp', 'ftps']
  66. def __init__(self, schemes=None, **kwargs):
  67. super(URLValidator, self).__init__(**kwargs)
  68. if schemes is not None:
  69. self.schemes = schemes
  70. def __call__(self, value):
  71. value = force_text(value)
  72. # Check first if the scheme is valid
  73. scheme = value.split('://')[0].lower()
  74. if scheme not in self.schemes:
  75. raise ValidationError(self.message, code=self.code)
  76. # Then check full URL
  77. try:
  78. super(URLValidator, self).__call__(value)
  79. except ValidationError as e:
  80. # Trivial case failed. Try for possible IDN domain
  81. if value:
  82. scheme, netloc, path, query, fragment = urlsplit(value)
  83. try:
  84. netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
  85. except UnicodeError: # invalid domain part
  86. raise e
  87. url = urlunsplit((scheme, netloc, path, query, fragment))
  88. super(URLValidator, self).__call__(url)
  89. else:
  90. raise
  91. else:
  92. url = value
  93. def validate_integer(value):
  94. try:
  95. int(value)
  96. except (ValueError, TypeError):
  97. raise ValidationError(_('Enter a valid integer.'), code='invalid')
  98. @deconstructible
  99. class EmailValidator(object):
  100. message = _('Enter a valid email address.')
  101. code = 'invalid'
  102. user_regex = re.compile(
  103. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$" # dot-atom
  104. r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"$)', # quoted-string
  105. re.IGNORECASE)
  106. domain_regex = re.compile(
  107. r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,}(?<!-))$',
  108. re.IGNORECASE)
  109. literal_regex = re.compile(
  110. # literal form, ipv4 or ipv6 address (SMTP 4.1.3)
  111. r'\[([A-f0-9:\.]+)\]$',
  112. re.IGNORECASE)
  113. domain_whitelist = ['localhost']
  114. def __init__(self, message=None, code=None, whitelist=None):
  115. if message is not None:
  116. self.message = message
  117. if code is not None:
  118. self.code = code
  119. if whitelist is not None:
  120. self.domain_whitelist = whitelist
  121. def __call__(self, value):
  122. value = force_text(value)
  123. if not value or '@' not in value:
  124. raise ValidationError(self.message, code=self.code)
  125. user_part, domain_part = value.rsplit('@', 1)
  126. if not self.user_regex.match(user_part):
  127. raise ValidationError(self.message, code=self.code)
  128. if (domain_part not in self.domain_whitelist and
  129. not self.validate_domain_part(domain_part)):
  130. # Try for possible IDN domain-part
  131. try:
  132. domain_part = domain_part.encode('idna').decode('ascii')
  133. if self.validate_domain_part(domain_part):
  134. return
  135. except UnicodeError:
  136. pass
  137. raise ValidationError(self.message, code=self.code)
  138. def validate_domain_part(self, domain_part):
  139. if self.domain_regex.match(domain_part):
  140. return True
  141. literal_match = self.literal_regex.match(domain_part)
  142. if literal_match:
  143. ip_address = literal_match.group(1)
  144. try:
  145. validate_ipv46_address(ip_address)
  146. return True
  147. except ValidationError:
  148. pass
  149. return False
  150. def __eq__(self, other):
  151. return isinstance(other, EmailValidator) and (self.domain_whitelist == other.domain_whitelist) and (self.message == other.message) and (self.code == other.code)
  152. validate_email = EmailValidator()
  153. slug_re = re.compile(r'^[-a-zA-Z0-9_]+$')
  154. validate_slug = RegexValidator(slug_re, _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
  155. ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
  156. validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid')
  157. def validate_ipv6_address(value):
  158. if not is_valid_ipv6_address(value):
  159. raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
  160. def validate_ipv46_address(value):
  161. try:
  162. validate_ipv4_address(value)
  163. except ValidationError:
  164. try:
  165. validate_ipv6_address(value)
  166. except ValidationError:
  167. raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
  168. ip_address_validator_map = {
  169. 'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
  170. 'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')),
  171. 'ipv6': ([validate_ipv6_address], _('Enter a valid IPv6 address.')),
  172. }
  173. def ip_address_validators(protocol, unpack_ipv4):
  174. """
  175. Depending on the given parameters returns the appropriate validators for
  176. the GenericIPAddressField.
  177. This code is here, because it is exactly the same for the model and the form field.
  178. """
  179. if protocol != 'both' and unpack_ipv4:
  180. raise ValueError(
  181. "You can only use `unpack_ipv4` if `protocol` is set to 'both'")
  182. try:
  183. return ip_address_validator_map[protocol.lower()]
  184. except KeyError:
  185. raise ValueError("The protocol '%s' is unknown. Supported: %s"
  186. % (protocol, list(ip_address_validator_map)))
  187. comma_separated_int_list_re = re.compile('^[\d,]+$')
  188. validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid')
  189. @deconstructible
  190. class BaseValidator(object):
  191. compare = lambda self, a, b: a is not b
  192. clean = lambda self, x: x
  193. message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).')
  194. code = 'limit_value'
  195. def __init__(self, limit_value):
  196. self.limit_value = limit_value
  197. def __call__(self, value):
  198. cleaned = self.clean(value)
  199. params = {'limit_value': self.limit_value, 'show_value': cleaned}
  200. if self.compare(cleaned, self.limit_value):
  201. raise ValidationError(self.message, code=self.code, params=params)
  202. def __eq__(self, other):
  203. return isinstance(other, self.__class__) and (self.limit_value == other.limit_value) and (self.message == other.message) and (self.code == other.code)
  204. @deconstructible
  205. class MaxValueValidator(BaseValidator):
  206. compare = lambda self, a, b: a > b
  207. message = _('Ensure this value is less than or equal to %(limit_value)s.')
  208. code = 'max_value'
  209. @deconstructible
  210. class MinValueValidator(BaseValidator):
  211. compare = lambda self, a, b: a < b
  212. message = _('Ensure this value is greater than or equal to %(limit_value)s.')
  213. code = 'min_value'
  214. @deconstructible
  215. class MinLengthValidator(BaseValidator):
  216. compare = lambda self, a, b: a < b
  217. clean = lambda self, x: len(x)
  218. message = ungettext_lazy(
  219. 'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
  220. 'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
  221. 'limit_value')
  222. code = 'min_length'
  223. @deconstructible
  224. class MaxLengthValidator(BaseValidator):
  225. compare = lambda self, a, b: a > b
  226. clean = lambda self, x: len(x)
  227. message = ungettext_lazy(
  228. 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).',
  229. 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).',
  230. 'limit_value')
  231. code = 'max_length'