validators.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import re
  2. from django.core.validators import _lazy_re_compile, BaseValidator, URLValidator
  3. class EnhancedURLValidator(URLValidator):
  4. """
  5. Extends Django's built-in URLValidator to permit the use of hostnames with no domain extension.
  6. """
  7. class AnyURLScheme(object):
  8. """
  9. A fake URL list which "contains" all scheme names abiding by the syntax defined in RFC 3986 section 3.1
  10. """
  11. def __contains__(self, item):
  12. if not item or not re.match(r'^[a-z][0-9a-z+\-.]*$', item.lower()):
  13. return False
  14. return True
  15. fqdn_re = URLValidator.hostname_re + URLValidator.domain_re + URLValidator.tld_re
  16. host_res = [URLValidator.ipv4_re, URLValidator.ipv6_re, fqdn_re, URLValidator.hostname_re]
  17. regex = _lazy_re_compile(
  18. r'^(?:[a-z0-9\.\-\+]*)://' # Scheme (previously enforced by AnyURLScheme or schemes kwarg)
  19. r'(?:\S+(?::\S*)?@)?' # HTTP basic authentication
  20. r'(?:' + '|'.join(host_res) + ')' # IPv4, IPv6, FQDN, or hostname
  21. r'(?::\d{2,5})?' # Port number
  22. r'(?:[/?#][^\s]*)?' # Path
  23. r'\Z', re.IGNORECASE)
  24. schemes = AnyURLScheme()
  25. class ExclusionValidator(BaseValidator):
  26. """
  27. Ensure that a field's value is not equal to any of the specified values.
  28. """
  29. message = 'This value may not be %(show_value)s.'
  30. def compare(self, a, b):
  31. return a in b