-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidators.py
70 lines (63 loc) · 2.59 KB
/
Validators.py
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
import re
from typing import Optional
class Validators:
# Validate floating point number such as latitude, longitude
@classmethod
def valid_float_in_range(cls, proposed_value: str,
min_value: float,
max_value: float) -> Optional[float]:
"""
Validate that a string is a floating point number in a given range
:param proposed_value: String to be tested
:param min_value: Minimum acceptable value
:param max_value: Maximum acceptable value
:return: Converted value if valid, None if not valid
"""
result: Optional[float] = None
try:
converted: float = float(proposed_value)
if (converted >= min_value) and (converted <= max_value):
result = converted
except ValueError:
# Let result go back as "none", indicating error
pass
return result
# Validate integer number
@classmethod
def valid_int_in_range(cls, proposed_value: str,
min_value: int,
max_value: int) -> Optional[int]:
"""
Validate that a string is an integer in a given range
:param proposed_value: String to be tested
:param min_value: Minimum acceptable value
:param max_value: Maximum acceptable value
:return: Converted value if valid, None if not valid
"""
result: Optional[int] = None
try:
converted: int = int(proposed_value)
if (converted >= min_value) and (converted <= max_value):
result = converted
except ValueError:
# Let result go back as "none", indicating error
pass
return result
@classmethod
def valid_file_name(cls, proposed_name,
min_length,
max_length) -> bool:
"""
Is the given string a valid file name (just the name, no extensions or slashes)?
:param proposed_name: Name to check
:param min_length: Minimum string length
:param max_length: Maximum string length
:return: Appears to be a valid file name?
"""
assert 0 < min_length <= max_length
result = False
if min_length <= len(proposed_name) <= max_length:
upper = proposed_name.upper()
matched = re.fullmatch("[A-Z0-9_\\-$()]*", upper)
result = bool(matched)
return result