-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvalidators.py
More file actions
141 lines (103 loc) · 4.8 KB
/
Copy pathvalidators.py
File metadata and controls
141 lines (103 loc) · 4.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""Input validation functions"""
from typing import Any, List, Optional, Union
from game.core.exceptions import ValidationException
def validate_integer(value: str, min_val: Optional[int] = None,
max_val: Optional[int] = None) -> int:
"""Validate and convert string to integer"""
try:
num = int(value)
if min_val is not None and num < min_val:
raise ValidationException(f"Value must be at least {min_val}")
if max_val is not None and num > max_val:
raise ValidationException(f"Value must be at most {max_val}")
return num
except ValueError:
raise ValidationException(f"'{value}' is not a valid integer")
def validate_float(value: str, min_val: Optional[float] = None,
max_val: Optional[float] = None) -> float:
"""Validate and convert string to float"""
try:
num = float(value)
if min_val is not None and num < min_val:
raise ValidationException(f"Value must be at least {min_val}")
if max_val is not None and num > max_val:
raise ValidationException(f"Value must be at most {max_val}")
return num
except ValueError:
raise ValidationException(f"'{value}' is not a valid number")
def validate_choice(value: str, choices: List[str], case_sensitive: bool = False) -> str:
"""Validate that value is in choices"""
if not case_sensitive:
value = value.lower()
choices = [c.lower() for c in choices]
if value not in choices:
choice_str = ", ".join(choices)
raise ValidationException(f"'{value}' is not valid. Choose from: {choice_str}")
return value
def validate_money(amount: int, available: int, min_amount: int = 0) -> bool:
"""Validate money transaction"""
if amount < min_amount:
raise ValidationException(f"Amount must be at least ${min_amount}")
if amount > available:
raise ValidationException(
f"Insufficient funds. Required: ${amount}, Available: ${available}"
)
return True
def validate_string(value: str, min_length: int = 1,
max_length: Optional[int] = None,
allowed_chars: Optional[str] = None) -> str:
"""Validate string"""
if len(value) < min_length:
raise ValidationException(f"String must be at least {min_length} characters")
if max_length is not None and len(value) > max_length:
raise ValidationException(f"String must be at most {max_length} characters")
if allowed_chars is not None:
invalid_chars = [c for c in value if c not in allowed_chars]
if invalid_chars:
raise ValidationException(f"Invalid characters: {invalid_chars}")
return value
def validate_range(value: int, min_val: int, max_val: int) -> int:
"""Validate value is within range"""
if value < min_val or value > max_val:
raise ValidationException(f"Value must be between {min_val} and {max_val}")
return value
def validate_not_empty(value: str, field_name: str = "Value") -> str:
"""Validate string is not empty"""
stripped = value.strip()
if not stripped:
raise ValidationException(f"{field_name} cannot be empty")
return stripped
def validate_yes_no(value: str) -> bool:
"""Validate yes/no input"""
normalized = value.lower()
if normalized in ("y", "yes"):
return True
elif normalized in ("n", "no"):
return False
else:
raise ValidationException("Please enter 'yes' or 'no'")
def validate_list(items: List[Any], min_length: int = 0,
max_length: Optional[int] = None) -> List[Any]:
"""Validate list"""
if len(items) < min_length:
raise ValidationException(f"List must have at least {min_length} items")
if max_length is not None and len(items) > max_length:
raise ValidationException(f"List must have at most {max_length} items")
return items
def validate_in_list(value: Any, items: List[Any], field_name: str = "Value") -> Any:
"""Validate value is in list"""
if value not in items:
raise ValidationException(f"{field_name} must be one of: {items}")
return value
def safe_input(prompt: str, validator_func=None, error_message: str = "Invalid input"):
"""Get input with validation"""
while True:
try:
user_input = input(prompt).strip()
if validator_func:
return validator_func(user_input)
return user_input
except ValidationException as e:
print(f"Error: {e}")
except Exception as e:
print(f"Error: {error_message}")