validation_utils.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import re
  2. def validate_color_hex(value):
  3. """
  4. Validates that a given value is a valid hex color code.
  5. Parameters:
  6. :value: The color code to validate.
  7. """
  8. if value is None:
  9. return value
  10. if value and not value.startswith("#"):
  11. value = f"#{value}"
  12. hex_pattern = re.compile(r"^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")
  13. if re.match(hex_pattern, value):
  14. return value
  15. else:
  16. raise ValueError(f"{value} is not a valid hex color code.")
  17. def validate_url(value):
  18. """
  19. Validates that a given value is a valid URL format using regex.
  20. Parameters:
  21. :value: The URL to validate.
  22. """
  23. if value is None:
  24. return value
  25. url_regex = re.compile(
  26. r"^(https?|ftp)://" # Protocol: http, https, or ftp
  27. r"((([A-Za-z0-9-]+\.)+[A-Za-z]{2,6})|" # Domain name
  28. r"(\d{1,3}\.){3}\d{1,3})" # OR IPv4
  29. r"(:\d+)?" # Port
  30. r"(/([A-Za-z0-9$_.+!*\'(),;?&=-]|%[0-9A-Fa-f]{2})*)*" # Path
  31. r"(\?([A-Za-z0-9$_.+!*\'(),;?&=-]|%[0-9A-Fa-f]{2})*)?" # Query string
  32. )
  33. if not url_regex.match(value):
  34. raise ValueError(f"'{value}' is not a valid URL.")
  35. # check if more than 255 characters
  36. if len(value) > 255:
  37. raise ValueError(
  38. "provided logo-url is too long. Maximum length is 255 characters."
  39. )
  40. return value