Practical Validation Patterns
Validation Strategy Overview
graph TD
A[Practical Validation Patterns] --> B[Input Validation]
A --> C[Data Transformation]
A --> D[Error Handling]
A --> E[Advanced Validation Techniques]
Multi-Level Validation Approach
class UserRegistration:
@classmethod
def validate_registration(cls, username, email, password):
## Validate username
cls._validate_username(username)
## Validate email
cls._validate_email(email)
## Validate password
cls._validate_password(password)
return {
'username': username,
'email': email,
'password': cls._hash_password(password)
}
@staticmethod
def _validate_username(username):
if not isinstance(username, str):
raise ValueError("Username must be a string")
if len(username) < 3 or len(username) > 20:
raise ValueError("Username must be 3-20 characters long")
@staticmethod
def _validate_email(email):
import re
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_regex, email):
raise ValueError("Invalid email format")
@staticmethod
def _validate_password(password):
if len(password) < 8:
raise ValueError("Password must be at least 8 characters")
if not any(char.isupper() for char in password):
raise ValueError("Password must contain uppercase letter")
if not any(char.isdigit() for char in password):
raise ValueError("Password must contain a number")
@staticmethod
def _hash_password(password):
import hashlib
return hashlib.sha256(password.encode()).hexdigest()
## Usage example
try:
user_data = UserRegistration.validate_registration(
"john_doe",
"[email protected]",
"SecurePass123"
)
print("Registration successful:", user_data)
except ValueError as e:
print("Validation Error:", str(e))
Validation with Type Conversion
class DataProcessor:
@classmethod
def process_numeric_input(cls, value):
## Validate and transform input
try:
## Attempt type conversion with validation
numeric_value = cls._convert_to_numeric(value)
## Additional range validation
cls._validate_range(numeric_value)
return numeric_value
except ValueError as e:
raise ValueError(f"Invalid input: {e}")
@staticmethod
def _convert_to_numeric(value):
## Handle different input types
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
## Remove whitespace and convert
cleaned_value = value.strip().replace(',', '.')
return float(cleaned_value)
raise ValueError("Cannot convert to numeric type")
@staticmethod
def _validate_range(value, min_val=0, max_val=1000):
if value < min_val or value > max_val:
raise ValueError(f"Value must be between {min_val} and {max_val}")
## Usage example
try:
result = DataProcessor.process_numeric_input("123.45")
print("Processed value:", result)
## Different input types
print(DataProcessor.process_numeric_input(100))
print(DataProcessor.process_numeric_input("1,000.50"))
except ValueError as e:
print("Processing Error:", str(e))
3. Advanced Validation Techniques
Conditional Validation Pattern
class ConfigurationValidator:
@classmethod
def validate_config(cls, config):
## Validate configuration with conditional rules
validated_config = {}
## Validate required fields
cls._validate_required_fields(config)
## Conditional validation based on environment
environment = config.get('environment', 'production')
if environment == 'production':
cls._validate_production_config(config)
elif environment == 'development':
cls._validate_development_config(config)
return config
@staticmethod
def _validate_required_fields(config):
required_fields = ['name', 'environment']
for field in required_fields:
if field not in config:
raise ValueError(f"Missing required field: {field}")
@staticmethod
def _validate_production_config(config):
## Stricter validation for production
if not config.get('security_key'):
raise ValueError("Production environment requires a security key")
@staticmethod
def _validate_development_config(config):
## More relaxed validation for development
config.setdefault('debug', True)
## Usage example
sample_config = {
'name': 'MyApp',
'environment': 'production',
'security_key': 'secret_key_123'
}
try:
validated_config = ConfigurationValidator.validate_config(sample_config)
print("Validated Configuration:", validated_config)
except ValueError as e:
print("Configuration Error:", str(e))
Validation Best Practices
Practice |
Description |
Recommendation |
Fail Fast |
Detect and report errors early |
Validate inputs immediately |
Clear Error Messages |
Provide informative error details |
Include specific validation criteria |
Flexible Validation |
Support multiple input types |
Use type conversion techniques |
Secure Validation |
Prevent potential security risks |
Sanitize and validate all inputs |
Key Takeaways
- Implement multi-level validation strategies
- Use type conversion and transformation
- Handle different input scenarios
- LabEx recommends comprehensive error handling
- Always prioritize input security and data integrity
By mastering these practical validation patterns, developers can create more robust and reliable Python applications.