-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidators.py
More file actions
88 lines (68 loc) · 2.74 KB
/
validators.py
File metadata and controls
88 lines (68 loc) · 2.74 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
from PyQt5.QtGui import QRegExpValidator, QIntValidator, QDoubleValidator, QRegularExpressionValidator
from PyQt5.QtCore import QRegExp, QRegularExpression
def get_name_validator():
"""
Returns a QRegExpValidator that allows letters (both uppercase and lowercase),
spaces, hyphens, and apostrophes. Suitable for validating names.
"""
name_regex = QRegExp("^[A-Za-zÀ-ÿ ,.'-]+$")
return QRegExpValidator(name_regex)
def get_id_validator():
"""
Returns a QIntValidator that only allows integer values between 0000 and 9999.
Ensures that the ID is a four-digit number.
"""
id_validator = QIntValidator(0, 9999)
return id_validator
def get_dob_validator():
"""
Returns a QRegExpValidator that enforces the YYYY-MM-DD date format.
Validates Date of Birth entries.
"""
dob_regex = QRegExp("^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$")
return QRegExpValidator(dob_regex)
def get_grade_validator():
"""
Returns a QRegularExpressionValidator that allows numbers between 0 and 100,
with up to two decimal places.
"""
# Regular expression explanation:
# ^ - start of string
# (100(\.00?)?) - matches 100 or 100.0 or 100.00
# | - OR
# ([0-9]{1,2}(\.[0-9]{1,2})?) - matches 0-99 with optional .0 or .00 etc.
# $ - end of string
regex = QRegularExpression(r"^(100(\.00?)?|[0-9]{1,2}(\.[0-9]{1,2})?)$")
grade_validator = QRegularExpressionValidator(regex)
return grade_validator
def get_positive_int_validator():
"""
Returns a QIntValidator that only allows positive integer values.
Useful for fields that require positive integers beyond a specific range.
"""
positive_int_validator = QIntValidator(1, 2147483647) # 32-bit integer max
return positive_int_validator
def pad_with_zeros(value, total_length=4):
"""
Pads the given number with leading zeros to ensure it has a specified total length.
Parameters:
value (int or str): The input number to pad.
total_length (int): The desired total length of the output string. Default is 4.
Returns:
str: The padded string with leading zeros.
Raises:
ValueError: If the input is not a valid integer or if it's negative.
"""
try:
# Convert the input to an integer
num = int(value)
if num < 0:
raise ValueError("Value cannot be negative.")
# Convert back to string with leading zeros
padded = f"{num:0{total_length}d}"
# If the number exceeds the total_length, truncate from the left
if len(padded) > total_length:
padded = padded[-total_length:]
return padded
except ValueError as e:
raise ValueError(f"Invalid input for padding: {value}. {e}")