Sitemap generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.1 KiB

4 years ago
  1. import re
  2. class ValidationFailure(BaseException):
  3. """
  4. class for Validation exceptions
  5. """
  6. domain_pattern = re.compile(
  7. r'^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|'
  8. r'([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|'
  9. r'([a-zA-Z0-9][-_.a-zA-Z0-9]{0,61}[a-zA-Z0-9]))\.'
  10. r'([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}.[a-zA-Z]{2,3})$'
  11. )
  12. def domain(value, raise_errors=True):
  13. """
  14. Return whether or not given value is a valid domain.
  15. If the value is valid domain name this function returns ``True``, otherwise
  16. :class:`~validators.ValidationFailure` or False if raise_errors muted.
  17. Examples::
  18. >>> domain('example.com')
  19. True
  20. >>> domain('example.com/')
  21. ValidationFailure(func=domain, ...)
  22. Supports IDN domains as well::
  23. >>> domain('xn----gtbspbbmkef.xn--p1ai')
  24. True
  25. :param value: domain string to validate
  26. :param raise_errors: raise errors or return False
  27. """
  28. if domain_pattern.match(value) is None:
  29. if raise_errors:
  30. raise ValidationFailure("{} is not valid domain".format(value))
  31. else:
  32. return False
  33. return True