validators.py 1.2 KB

12345678910111213141516171819202122232425262728
  1. import re
  2. from django.core.validators import _lazy_re_compile, 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()