Practical Validation Patterns
Comprehensive Numeric Data Validation Approaches
1. Validation Decorator Pattern
def validate_numeric(min_val=None, max_val=None, numeric_type=float):
"""
Decorator for numeric validation
Args:
min_val (numeric, optional): Minimum allowed value
max_val (numeric, optional): Maximum allowed value
numeric_type (type, optional): Expected numeric type
"""
def decorator(func):
def wrapper(*args, **kwargs):
for arg in args:
if not isinstance(arg, numeric_type):
raise TypeError(f"Expected {numeric_type}, got {type(arg)}")
if min_val is not None and arg < min_val:
raise ValueError(f"Value must be >= {min_val}")
if max_val is not None and arg > max_val:
raise ValueError(f"Value must be <= {max_val}")
return func(*args, **kwargs)
return wrapper
return decorator
## Example usage
@validate_numeric(min_val=0, max_val=100, numeric_type=float)
def calculate_discount(price):
return price * 0.9
Validation Strategy Workflow
graph TD
A[Input Numeric Data] --> B{Type Validation}
B --> |Valid Type| C{Range Check}
B --> |Invalid Type| D[Reject Data]
C --> |Within Range| E{Precision Validation}
C --> |Out of Range| D
E --> |Pass| F[Accept Data]
E --> |Fail| D
2. MongoDB Aggregation Validation
def validate_numeric_aggregation(collection, field, criteria):
"""
Perform numeric validation using MongoDB aggregation
Args:
collection: MongoDB collection
field (str): Field to validate
criteria (dict): Validation criteria
Returns:
list: Validation results
"""
validation_pipeline = [
{'$match': {field: {'$exists': True}}},
{'$group': {
'_id': None,
'min_value': {'$min': f'${field}'},
'max_value': {'$max': f'${field}'},
'avg_value': {'$avg': f'${field}'}
}},
{'$project': {
'is_valid': {
'$and': [
{'$gte': [f'${field}', criteria.get('min', float('-inf'))]},
{'$lte': [f'${field}', criteria.get('max', float('inf'))]}
]
}
}}
]
return list(collection.aggregate(validation_pipeline))
Validation Pattern Comparison
Pattern |
Complexity |
Performance |
Flexibility |
Decorator |
Low |
High |
Medium |
Aggregation |
High |
Medium |
High |
Schema Validation |
Medium |
Low |
Low |
3. Comprehensive Validation Class
class NumericValidator:
@staticmethod
def validate_range(value, min_val=None, max_val=None):
"""
Validate numeric range
Args:
value (numeric): Value to validate
min_val (numeric, optional): Minimum allowed value
max_val (numeric, optional): Maximum allowed value
Returns:
bool: Validation result
"""
if min_val is not None and value < min_val:
return False
if max_val is not None and value > max_val:
return False
return True
@staticmethod
def validate_precision(value, decimal_places=2):
"""
Validate numeric precision
Args:
value (numeric): Value to validate
decimal_places (int): Maximum allowed decimal places
Returns:
bool: Precision validation result
"""
return len(str(value).split('.')[-1]) <= decimal_places
## Example usage
validator = NumericValidator()
print(validator.validate_range(50, 0, 100)) ## True
print(validator.validate_precision(99.999, 2)) ## False
Advanced Validation Considerations
- Implement multi-layer validation
- Use type hints and static type checking
- Log validation failures
- Handle edge cases gracefully
Best Practices for LabEx Numeric Validation
- Combine multiple validation techniques
- Use type-specific validation strategies
- Implement comprehensive error handling
- Optimize performance through efficient validation methods
By mastering these practical validation patterns, you'll develop robust and reliable numeric data management strategies in MongoDB with LabEx's recommended approach.