-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.py
More file actions
81 lines (59 loc) · 2 KB
/
validation.py
File metadata and controls
81 lines (59 loc) · 2 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
from dataclasses import dataclass
from typing import Callable, List
# =========================
# Validation Result
# =========================
@dataclass
class ValidationResult:
is_valid: bool
message: str = ""
# =========================
# Types
# =========================
Validator = Callable[[str], ValidationResult]
# =========================
# Validation Engine
# =========================
def validate(
value: str,
validators: Iterable[Validator],
fail_fast: bool = True
) -> list[ValidationResult]:
"""
Runs a sequence of validation rules over a given input value.
This function applies each validator to the input string and collects
validation results. It supports two execution modes:
1. Fail-fast mode:
Stops at the first validation failure and returns immediately.
2. Aggregate mode:
Runs all validators and returns all validation failures.
Args:
value (str):
The input value to be validated.
validators (Iterable[Validator]):
A collection of validator functions. Each validator must accept
a string and return a ValidationResult.
fail_fast (bool, optional):
If True, validation stops at the first failure.
If False, all validators are executed and all failures are collected.
Default is True.
Returns:
list[ValidationResult]:
A list of validation results that represent failures.
If the list is empty, the value is considered valid.
"""
results = []
for validator in validators:
result = validator(value)
if not result.is_valid:
results.append(result)
if fail_fast:
return results
return results
# =========================
# Input validators
# =========================
def is_not_blank(value: str) -> ValidationResult:
if not value:
return ValidationResult(False, "Input must not be blank!")
return ValidationResult(True)