PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/django/core/validators.py

https://github.com/andnils/django
Python | 275 lines | 229 code | 37 blank | 9 comment | 30 complexity | e53323d02553b07f4c6a53361300cd2a MD5 | raw file
Possible License(s): BSD-3-Clause
  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 isinstance(other, RegexValidator) and (self.regex == other.regex) and (self.message == other.message) and (self.code == other.code)
  45. @deconstructible
  46. class URLValidator(RegexValidator):
  47. regex = re.compile(
  48. r'^(?:[a-z0-9\.\-]*)://' # scheme is validated separately
  49. r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
  50. r'localhost|' # localhost...
  51. r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
  52. r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
  53. r'(?::\d+)?' # optional port
  54. r'(?:/?|[/?]\S+)$', re.IGNORECASE)
  55. message = _('Enter a valid URL.')
  56. schemes = ['http', 'https', 'ftp', 'ftps']
  57. def __init__(self, schemes=None, **kwargs):
  58. super(URLValidator, self).__init__(**kwargs)
  59. if schemes is not None:
  60. self.schemes = schemes
  61. def __call__(self, value):
  62. value = force_text(value)
  63. # Check first if the scheme is valid
  64. scheme = value.split('://')[0].lower()
  65. if scheme not in self.schemes:
  66. raise ValidationError(self.message, code=self.code)
  67. # Then check full URL
  68. try:
  69. super(URLValidator, self).__call__(value)
  70. except ValidationError as e:
  71. # Trivial case failed. Try for possible IDN domain
  72. if value:
  73. scheme, netloc, path, query, fragment = urlsplit(value)
  74. try:
  75. netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
  76. except UnicodeError: # invalid domain part
  77. raise e
  78. url = urlunsplit((scheme, netloc, path, query, fragment))
  79. super(URLValidator, self).__call__(url)
  80. else:
  81. raise
  82. else:
  83. url = value
  84. def validate_integer(value):
  85. try:
  86. int(value)
  87. except (ValueError, TypeError):
  88. raise ValidationError(_('Enter a valid integer.'), code='invalid')
  89. @deconstructible
  90. class EmailValidator(object):
  91. message = _('Enter a valid email address.')
  92. code = 'invalid'
  93. user_regex = re.compile(
  94. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$" # dot-atom
  95. r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"$)', # quoted-string
  96. re.IGNORECASE)
  97. domain_regex = re.compile(
  98. r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$',
  99. re.IGNORECASE)
  100. literal_regex = re.compile(
  101. # literal form, ipv4 or ipv6 address (SMTP 4.1.3)
  102. r'\[([A-f0-9:\.]+)\]$',
  103. re.IGNORECASE)
  104. domain_whitelist = ['localhost']
  105. def __init__(self, message=None, code=None, whitelist=None):
  106. if message is not None:
  107. self.message = message
  108. if code is not None:
  109. self.code = code
  110. if whitelist is not None:
  111. self.domain_whitelist = whitelist
  112. def __call__(self, value):
  113. value = force_text(value)
  114. if not value or '@' not in value:
  115. raise ValidationError(self.message, code=self.code)
  116. user_part, domain_part = value.rsplit('@', 1)
  117. if not self.user_regex.match(user_part):
  118. raise ValidationError(self.message, code=self.code)
  119. if (not domain_part in self.domain_whitelist and
  120. not self.validate_domain_part(domain_part)):
  121. # Try for possible IDN domain-part
  122. try:
  123. domain_part = domain_part.encode('idna').decode('ascii')
  124. if self.validate_domain_part(domain_part):
  125. return
  126. except UnicodeError:
  127. pass
  128. raise ValidationError(self.message, code=self.code)
  129. def validate_domain_part(self, domain_part):
  130. if self.domain_regex.match(domain_part):
  131. return True
  132. literal_match = self.literal_regex.match(domain_part)
  133. if literal_match:
  134. ip_address = literal_match.group(1)
  135. try:
  136. validate_ipv46_address(ip_address)
  137. return True
  138. except ValidationError:
  139. pass
  140. return False
  141. def __eq__(self, other):
  142. return isinstance(other, EmailValidator) and (self.domain_whitelist == other.domain_whitelist) and (self.message == other.message) and (self.code == other.code)
  143. validate_email = EmailValidator()
  144. slug_re = re.compile(r'^[-a-zA-Z0-9_]+$')
  145. validate_slug = RegexValidator(slug_re, _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
  146. 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}$')
  147. validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid')
  148. def validate_ipv6_address(value):
  149. if not is_valid_ipv6_address(value):
  150. raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
  151. def validate_ipv46_address(value):
  152. try:
  153. validate_ipv4_address(value)
  154. except ValidationError:
  155. try:
  156. validate_ipv6_address(value)
  157. except ValidationError:
  158. raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
  159. ip_address_validator_map = {
  160. 'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
  161. 'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')),
  162. 'ipv6': ([validate_ipv6_address], _('Enter a valid IPv6 address.')),
  163. }
  164. def ip_address_validators(protocol, unpack_ipv4):
  165. """
  166. Depending on the given parameters returns the appropriate validators for
  167. the GenericIPAddressField.
  168. This code is here, because it is exactly the same for the model and the form field.
  169. """
  170. if protocol != 'both' and unpack_ipv4:
  171. raise ValueError(
  172. "You can only use `unpack_ipv4` if `protocol` is set to 'both'")
  173. try:
  174. return ip_address_validator_map[protocol.lower()]
  175. except KeyError:
  176. raise ValueError("The protocol '%s' is unknown. Supported: %s"
  177. % (protocol, list(ip_address_validator_map)))
  178. comma_separated_int_list_re = re.compile('^[\d,]+$')
  179. validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid')
  180. @deconstructible
  181. class BaseValidator(object):
  182. compare = lambda self, a, b: a is not b
  183. clean = lambda self, x: x
  184. message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).')
  185. code = 'limit_value'
  186. def __init__(self, limit_value):
  187. self.limit_value = limit_value
  188. def __call__(self, value):
  189. cleaned = self.clean(value)
  190. params = {'limit_value': self.limit_value, 'show_value': cleaned}
  191. if self.compare(cleaned, self.limit_value):
  192. raise ValidationError(self.message, code=self.code, params=params)
  193. def __eq__(self, other):
  194. return isinstance(other, self.__class__) and (self.limit_value == other.limit_value) and (self.message == other.message) and (self.code == other.code)
  195. @deconstructible
  196. class MaxValueValidator(BaseValidator):
  197. compare = lambda self, a, b: a > b
  198. message = _('Ensure this value is less than or equal to %(limit_value)s.')
  199. code = 'max_value'
  200. @deconstructible
  201. class MinValueValidator(BaseValidator):
  202. compare = lambda self, a, b: a < b
  203. message = _('Ensure this value is greater than or equal to %(limit_value)s.')
  204. code = 'min_value'
  205. @deconstructible
  206. class MinLengthValidator(BaseValidator):
  207. compare = lambda self, a, b: a < b
  208. clean = lambda self, x: len(x)
  209. message = ungettext_lazy(
  210. 'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
  211. 'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
  212. 'limit_value')
  213. code = 'min_length'
  214. @deconstructible
  215. class MaxLengthValidator(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 most %(limit_value)d character (it has %(show_value)d).',
  220. 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).',
  221. 'limit_value')
  222. code = 'max_length'