Validation Techniques
Advanced Range Validation Methods
Decorator-Based Validation
def range_validator(min_val, max_val):
def decorator(func):
def wrapper(value):
if min_val <= value <= max_val:
return func(value)
raise ValueError(f"Value must be between {min_val} and {max_val}")
return wrapper
return decorator
@range_validator(0, 100)
def process_score(score):
print(f"Processing score: {score}")
## Usage examples
process_score(85) ## Valid
## process_score(150) ## Raises ValueError
Comprehensive Validation Strategies
Multiple Condition Validation
def validate_complex_range(value, conditions):
for condition in conditions:
if not condition(value):
return False
return True
## Example of multiple range checks
def check_temperature(temp):
conditions = [
lambda x: x >= -50, ## Minimum temperature
lambda x: x <= 50, ## Maximum temperature
lambda x: x != 0 ## Exclude zero
]
return validate_complex_range(temp, conditions)
## Validation demonstration
print(check_temperature(25)) ## True
print(check_temperature(-60)) ## False
Validation Techniques Comparison
Technique |
Pros |
Cons |
Simple Comparison |
Easy to implement |
Limited flexibility |
Decorator |
Reusable |
Slight performance overhead |
Multiple Conditions |
Highly flexible |
More complex |
Validation Flow Diagram
graph TD
A[Input Value] --> B{Multiple Conditions}
B -->|Check 1| C{Condition Met?}
B -->|Check 2| D{Condition Met?}
B -->|Check N| E{Condition Met?}
C -->|Yes| F[Continue Validation]
C -->|No| G[Validation Fails]
D -->|Yes| F
D -->|No| G
E -->|Yes| F
E -->|No| G
Error Handling Techniques
class RangeValidationError(ValueError):
"""Custom exception for range validation"""
def __init__(self, value, min_val, max_val):
self.value = value
self.min_val = min_val
self.max_val = max_val
super().__init__(f"Value {value} out of range [{min_val}, {max_val}]")
def strict_range_validator(value, min_val, max_val):
try:
if value < min_val or value > max_val:
raise RangeValidationError(value, min_val, max_val)
return True
except RangeValidationError as e:
print(f"Validation Error: {e}")
return False
## Usage
strict_range_validator(75, 0, 100) ## True
strict_range_validator(150, 0, 100) ## Prints error, returns False
At LabEx, we recommend choosing validation techniques based on:
- Complexity of validation rules
- Performance requirements
- Readability of code