validators.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import ipaddress
  2. from urllib.parse import urlparse
  3. def url(value: str) -> bool:
  4. """
  5. Validates whether the given string is a properly formatted URL.
  6. This function checks if the provided string has a valid URL scheme
  7. (e.g., 'http', 'https') and a valid hostname (e.g., 'localhost', 'example.com').
  8. Args:
  9. value (str): The URL string to be validated.
  10. Returns:
  11. bool: True if the string is a valid URL with a non-empty scheme and hostname,
  12. False otherwise.
  13. """
  14. parsed_url = urlparse(value)
  15. if parsed_url.scheme and parsed_url.hostname:
  16. return True
  17. return False
  18. def ip(value: str) -> bool:
  19. """
  20. Validates whether the given string is a properly formatted IP address.
  21. This function checks if the provided string is a valid IPv4 or IPv6 address.
  22. Args:
  23. value (str): The IP address string to be validated.
  24. Returns:
  25. bool: True if the string is a valid IP address, False otherwise.
  26. """
  27. try:
  28. ipaddress.ip_address(value)
  29. return True
  30. except ValueError:
  31. return False