Python Color Validation
Implementing Robust Hex Color Validation
Complete Validation Function
def validate_hex_color(color):
"""
Comprehensive hex color validation function
Args:
color (str): Color string to validate
Returns:
bool: True if valid hex color, False otherwise
"""
## Remove '#' prefix if present
color = color.lstrip('#')
## Check valid lengths
if len(color) not in [3, 6]:
return False
## Validate hex characters
try:
int(color, 16)
return True
except ValueError:
return False
Validation Techniques
1. Regex-based Validation
import re
def validate_hex_color_regex(color):
hex_pattern = r'^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$'
return bool(re.match(hex_pattern, color))
2. Type Conversion Validation
def validate_hex_to_rgb(color):
"""
Convert hex color to RGB values
Args:
color (str): Hex color string
Returns:
tuple: RGB values or None if invalid
"""
color = color.lstrip('#')
try:
## Handle 3-digit and 6-digit formats
if len(color) == 3:
r = int(color[0] * 2, 16)
g = int(color[1] * 2, 16)
b = int(color[2] * 2, 16)
elif len(color) == 6:
r = int(color[0:2], 16)
g = int(color[2:4], 16)
b = int(color[4:6], 16)
else:
return None
return (r, g, b)
except ValueError:
return None
Validation Workflow
graph TD
A[Input Color] --> B{Remove '#'}
B --> C{Check Length}
C --> |Invalid| D[Return False]
C --> |Valid| E{Validate Hex Digits}
E --> |Invalid| D
E --> |Valid| F[Return True/RGB Values]
Validation Strategies Comparison
Method |
Complexity |
Performance |
Flexibility |
Regex |
Low |
Medium |
High |
Manual |
Medium |
High |
Very High |
Type Conversion |
High |
Low |
Medium |
Advanced Validation Class
class ColorValidator:
@staticmethod
def validate(color):
"""
Advanced color validation method
Args:
color (str): Color to validate
Returns:
dict: Validation result with details
"""
result = {
'is_valid': False,
'rgb': None,
'format': None
}
color = color.lstrip('#')
if len(color) in [3, 6]:
try:
int(color, 16)
result['is_valid'] = True
result['format'] = f"{len(color)}-digit"
result['rgb'] = validate_hex_to_rgb(f"#{color}")
except ValueError:
pass
return result
## Example usage
validator = ColorValidator()
print(validator.validate("#FF0000"))
Best Practices
- Handle both 3 and 6-digit formats
- Support optional '#' prefix
- Provide informative validation results
- Consider performance for large-scale applications
LabEx Recommendation
In LabEx programming courses, mastering hex color validation demonstrates advanced string processing and type conversion skills essential for real-world software development.