1 # Unix SMB/CIFS implementation.
5 # Copyright (C) Catalyst.Net Ltd. 2023
7 # Written by Rob van der Linde <rob@catalyst.net.nz>
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 from abc
import ABCMeta
, abstractmethod
26 class ValidationError(Exception):
30 class Validator(metaclass
=ABCMeta
):
33 def __call__(self
, field
, value
):
37 class Range(Validator
):
38 """Checks if the value is within range min ... max."""
40 def __init__(self
, min=None, max=None):
41 if min is None and max is None:
42 raise ValueError("Range without a min and max doesn't make sense.")
47 def __call__(self
, field
, value
):
48 """Check if value is within the range min ... max.
50 It is possible to omit min, or omit max, in which case a more
51 tailored error message is returned.
53 if self
.min is not None and self
.max is None:
55 raise ValidationError(f
"{field} must be at least {self.min}")
57 elif self
.min is None and self
.max is not None:
59 raise ValidationError(
60 f
"{field} cannot be greater than {self.max}")
62 elif self
.min is not None and self
.max is not None:
63 if value
< self
.min or value
> self
.max:
64 raise ValidationError(
65 f
"{field} must be between {self.min} and {self.max}")
68 class OneOf(Validator
):
69 """Checks if the value is in a list of possible choices."""
71 def __init__(self
, choices
):
72 self
.choices
= sorted(choices
)
74 def __call__(self
, field
, value
):
75 if value
not in self
.choices
:
76 allowed_choices
= ", ".join(self
.choices
)
77 raise ValidationError(f
"{field} must be one of: {allowed_choices}")