Validation Strategies
Input validation is a critical process to ensure data integrity, security, and proper application functionality. Effective validation prevents potential errors and security vulnerabilities.
Basic Validation Techniques
Length Validation
def validate_length(input_string, min_length=3, max_length=50):
return min_length <= len(input_string) <= max_length
## Example usage
username = input("Enter username: ")
if validate_length(username):
print("Valid username length")
else:
print("Invalid username length")
Type Validation
def validate_type(input_value, expected_type):
try:
converted_value = expected_type(input_value)
return True
except ValueError:
return False
## Example
age_input = input("Enter your age: ")
is_valid_age = validate_type(age_input, int)
Advanced Validation Strategies
Regular Expression Validation
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
## Usage
email = input("Enter email address: ")
if validate_email(email):
print("Valid email format")
else:
print("Invalid email format")
Validation Flow
graph TD
A[User Input] --> B{Input Validation}
B -->|Length Check| C{Length Valid?}
B -->|Type Check| D{Type Valid?}
B -->|Pattern Check| E{Pattern Matches?}
C -->|Yes| F[Further Processing]
C -->|No| G[Reject Input]
D -->|Yes| F
D -->|No| G
E -->|Yes| F
E -->|No| G
Validation Strategies Comparison
Strategy |
Complexity |
Use Case |
Performance |
Length Check |
Low |
Basic input sizing |
Fast |
Type Validation |
Medium |
Numeric/Specific types |
Moderate |
Regex Validation |
High |
Complex pattern matching |
Slower |
Key Validation Principles
- Always validate user input
- Use multiple validation layers
- Provide clear error messages
- Sanitize inputs before processing
Error Handling Approach
def safe_input_validation(prompt, validator):
while True:
user_input = input(prompt)
if validator(user_input):
return user_input
print("Invalid input. Please try again.")
## Example usage with custom validator
def is_positive_number(value):
return value.isdigit() and int(value) > 0
age = safe_input_validation("Enter positive age: ", is_positive_number)
At LabEx, we emphasize robust input validation as a cornerstone of secure software development.