PageRenderTime 396ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/django/core/validators.py

https://github.com/etianen/django
Python | 289 lines | 241 code | 37 blank | 11 comment | 31 complexity | 1ef8654553ba7a25b9391d58d8178455 MD5 | raw file
  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. # max length of the domain is 249: 254 (max email length) minus one
  108. # period, two characters for the TLD, @ sign, & one character before @.
  109. r'(?:[A-Z0-9](?:[A-Z0-9-]{0,247}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,}(?<!-))$',
  110. re.IGNORECASE)
  111. literal_regex = re.compile(
  112. # literal form, ipv4 or ipv6 address (SMTP 4.1.3)
  113. r'\[([A-f0-9:\.]+)\]$',
  114. re.IGNORECASE)
  115. domain_whitelist = ['localhost']
  116. def __init__(self, message=None, code=None, whitelist=None):
  117. if message is not None:
  118. self.message = message
  119. if code is not None:
  120. self.code = code
  121. if whitelist is not None:
  122. self.domain_whitelist = whitelist
  123. def __call__(self, value):
  124. value = force_text(value)
  125. if not value or '@' not in value:
  126. raise ValidationError(self.message, code=self.code)
  127. user_part, domain_part = value.rsplit('@', 1)
  128. if not self.user_regex.match(user_part):
  129. raise ValidationError(self.message, code=self.code)
  130. if (domain_part not in self.domain_whitelist and
  131. not self.validate_domain_part(domain_part)):
  132. # Try for possible IDN domain-part
  133. try:
  134. domain_part = domain_part.encode('idna').decode('ascii')
  135. if self.validate_domain_part(domain_part):
  136. return
  137. except UnicodeError:
  138. pass
  139. raise ValidationError(self.message, code=self.code)
  140. def validate_domain_part(self, domain_part):
  141. if self.domain_regex.match(domain_part):
  142. return True
  143. literal_match = self.literal_regex.match(domain_part)
  144. if literal_match:
  145. ip_address = literal_match.group(1)
  146. try:
  147. validate_ipv46_address(ip_address)
  148. return True
  149. except ValidationError:
  150. pass
  151. return False
  152. def __eq__(self, other):
  153. return isinstance(other, EmailValidator) and (self.domain_whitelist == other.domain_whitelist) and (self.message == other.message) and (self.code == other.code)
  154. validate_email = EmailValidator()
  155. slug_re = re.compile(r'^[-a-zA-Z0-9_]+$')
  156. validate_slug = RegexValidator(slug_re, _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
  157. 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}$')
  158. validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid')
  159. def validate_ipv6_address(value):
  160. if not is_valid_ipv6_address(value):
  161. raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
  162. def validate_ipv46_address(value):
  163. try:
  164. validate_ipv4_address(value)
  165. except ValidationError:
  166. try:
  167. validate_ipv6_address(value)
  168. except ValidationError:
  169. raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
  170. ip_address_validator_map = {
  171. 'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
  172. 'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')),
  173. 'ipv6': ([validate_ipv6_address], _('Enter a valid IPv6 address.')),
  174. }
  175. def ip_address_validators(protocol, unpack_ipv4):
  176. """
  177. Depending on the given parameters returns the appropriate validators for
  178. the GenericIPAddressField.
  179. This code is here, because it is exactly the same for the model and the form field.
  180. """
  181. if protocol != 'both' and unpack_ipv4:
  182. raise ValueError(
  183. "You can only use `unpack_ipv4` if `protocol` is set to 'both'")
  184. try:
  185. return ip_address_validator_map[protocol.lower()]
  186. except KeyError:
  187. raise ValueError("The protocol '%s' is unknown. Supported: %s"
  188. % (protocol, list(ip_address_validator_map)))
  189. comma_separated_int_list_re = re.compile('^[\d,]+$')
  190. validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid')
  191. @deconstructible
  192. class BaseValidator(object):
  193. compare = lambda self, a, b: a is not b
  194. clean = lambda self, x: x
  195. message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).')
  196. code = 'limit_value'
  197. def __init__(self, limit_value, message=None):
  198. self.limit_value = limit_value
  199. if message:
  200. self.message = message
  201. def __call__(self, value):
  202. cleaned = self.clean(value)
  203. params = {'limit_value': self.limit_value, 'show_value': cleaned, 'value': value}
  204. if self.compare(cleaned, self.limit_value):
  205. raise ValidationError(self.message, code=self.code, params=params)
  206. def __eq__(self, other):
  207. return isinstance(other, self.__class__) and (self.limit_value == other.limit_value) and (self.message == other.message) and (self.code == other.code)
  208. @deconstructible
  209. class MaxValueValidator(BaseValidator):
  210. compare = lambda self, a, b: a > b
  211. message = _('Ensure this value is less than or equal to %(limit_value)s.')
  212. code = 'max_value'
  213. @deconstructible
  214. class MinValueValidator(BaseValidator):
  215. compare = lambda self, a, b: a < b
  216. message = _('Ensure this value is greater than or equal to %(limit_value)s.')
  217. code = 'min_value'
  218. @deconstructible
  219. class MinLengthValidator(BaseValidator):
  220. compare = lambda self, a, b: a < b
  221. clean = lambda self, x: len(x)
  222. message = ungettext_lazy(
  223. 'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
  224. 'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
  225. 'limit_value')
  226. code = 'min_length'
  227. @deconstructible
  228. class MaxLengthValidator(BaseValidator):
  229. compare = lambda self, a, b: a > b
  230. clean = lambda self, x: len(x)
  231. message = ungettext_lazy(
  232. 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).',
  233. 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).',
  234. 'limit_value')
  235. code = 'max_length'