Advanced Validation
Comprehensive Validation Strategies
Decorator-Based Validation
def validate_type(expected_type):
def decorator(func):
def wrapper(self, value):
if not isinstance(value, expected_type):
raise TypeError(f"Expected {expected_type.__name__}, got {type(value).__name__}")
return func(self, value)
return wrapper
return decorator
class StrictUser:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
@validate_type(str)
def name(self, value):
if len(value) < 2:
raise ValueError("Name must be at least 2 characters long")
self._name = value
Validation Workflow
flowchart TD
A[Input Received] --> B{Type Check}
B --> |Pass| C{Range Validation}
B --> |Fail| D[TypeError]
C --> |Pass| E{Custom Rules}
C --> |Fail| F[ValueError]
E --> |Pass| G[Set Value]
E --> |Fail| H[Custom Exception]
Advanced Validation Techniques
Technique |
Description |
Example Use Case |
Type Checking |
Ensure correct data type |
Form inputs |
Range Validation |
Limit value boundaries |
Numerical constraints |
Pattern Matching |
Validate string formats |
Email, phone numbers |
Dependency Validation |
Cross-field validation |
Password confirmation |
Complex Validation Example
class ComplexPassword:
def __init__(self):
self._password = None
@property
def password(self):
return self._password
@password.setter
def password(self, value):
## Comprehensive password validation
if not isinstance(value, str):
raise TypeError("Password must be a string")
if len(value) < 8:
raise ValueError("Password must be at least 8 characters")
import re
## Check for uppercase
if not re.search(r'[A-Z]', value):
raise ValueError("Password must contain at least one uppercase letter")
## Check for lowercase
if not re.search(r'[a-z]', value):
raise ValueError("Password must contain at least one lowercase letter")
## Check for digit
if not re.search(r'\d', value):
raise ValueError("Password must contain at least one digit")
## Check for special character
if not re.search(r'[!@#$%^&*(),.?":{}|<>]', value):
raise ValueError("Password must contain at least one special character")
self._password = value
Validation Composition
class UserProfile:
def __init__(self):
self._age = None
self._email = None
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, int):
raise TypeError("Age must be an integer")
if value < 18 or value > 120:
raise ValueError("Invalid age range")
self._age = value
@property
def email(self):
return self._email
@email.setter
def email(self, value):
import re
email_regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_regex, value):
raise ValueError("Invalid email format")
self._email = value
Best Practices
- Implement multiple layers of validation
- Provide clear, specific error messages
- Use type hints and docstrings
- Consider performance implications
LabEx recommends practicing these advanced validation techniques to create more robust and secure Python applications.