-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidators.py
253 lines (173 loc) · 5.89 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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""
Validators.
"""
import re
import six
from rest_framework.serializers.exceptions import ValidationError
class BaseValidator(object):
"""
base class for validator.
"""
message = ''
def __init__(self, message=None):
"""
Base class for validator.
:param str message: Error message.
"""
self.message = message or self.message
def __call__(self, value):
"""
Validation.
:param object value: Object for validation.
"""
raise NotImplementedError('`.__call__(self, value)` must be implemented.')
class RequiredValidator(BaseValidator):
"""
Validator on required field.
"""
message = 'This field is required.'
def __call__(self, value):
"""
Validation.
:param iter value: Object for validation.
:raise ValidationError: If not valid data.
"""
if value is None:
raise ValidationError(self.message)
class MinLengthValidator(BaseValidator):
"""
Validator for minimum length.
"""
message = 'The value must be longer than {min_length}.'
def __init__(self, min_length, *args, **kwargs):
"""
Validator.
:param int min_length: Minimum length.
"""
super().__init__(*args, **kwargs)
self.min_length = int(min_length)
def __call__(self, value):
"""
Validation.
:param iter value: Object for validation.
:raise ValidationError: If not valid data.
"""
if len(value) < self.min_length:
raise ValidationError(self.message.format(min_length=self.min_length))
class MaxLengthValidator(BaseValidator):
"""
Validator for maximum length.
"""
message = 'The value must be shorter than {max_length}.'
def __init__(self, max_length, *args, **kwargs):
"""
Validator for maximum length.
:param int min_length: Maximum length.
"""
super().__init__(*args, **kwargs)
self.max_length = int(max_length)
def __call__(self, value):
"""
Validation.
:param iter value: Object for validation.
:raise ValidationError: If not valid data.
"""
if len(value) > self.max_length:
raise ValidationError(self.message.format(max_length=self.max_length))
class MinValueValidator(BaseValidator):
"""
Validator for minimal value.
"""
message = 'The value must be greater than or equal to {min_value}.'
def __init__(self, min_value, *args, **kwargs):
"""
Validator for minimal value.
:param object min_value: Minimum value.
"""
super().__init__(*args, **kwargs)
self.min_value = min_value
def __call__(self, value):
"""
Validation.
:param object value: Value for validation.
:raise ValidationError: If not valid data.
"""
if value < self.min_value:
raise ValidationError(self.message.format(min_value=self.min_value))
class MaxValueValidator(BaseValidator):
"""
Validator for maximum value.
"""
message = 'The value must be less than or equal to {max_value}.'
def __init__(self, max_value, *args, **kwargs):
"""
Validator for maximum value.
:param object max_value: Maximum value.
"""
super().__init__(*args, **kwargs)
self.max_value = max_value
def __call__(self, value):
"""
Validation.
:param object value: Value for validation.
:raise ValidationError: If not valid data.
"""
if value > self.max_value:
raise ValidationError(self.message.format(max_value=self.max_value))
class RegexValidator(BaseValidator):
"""
Validator for check regex raw.
"""
regex = ''
message = 'Enter a valid value.'
inverse_match = False
flags = 0
def __init__(self, regex, inverse_match=None, flags=None, *args, **kwargs):
"""
Validator for check regex raw.
:param str regex: Regex for check.
:param bool inverse_match: Reverse check result.
:param int flags: Flags for compile regular.
"""
super().__init__(*args, **kwargs)
if regex is not None:
self.regex = regex
if inverse_match is not None:
self.inverse_match = inverse_match
if flags is not None:
self.flags = flags
if self.flags and not isinstance(self.regex, six.string_types):
raise TypeError("If the flags are set, regex must be a regular expression string.")
self.regex = re.compile(self.regex, self.flags)
def __call__(self, value):
"""
Validate that the input contains a match for the regular expression
if inverse_match is False, otherwise raise ValidationError.
:param object value: Value for validation.
:raise: ValidationError: If not valid data.
"""
if not (self.inverse_match is not bool(self.regex.search(value))):
raise ValidationError(self.message)
class ChoiceValidator(BaseValidator):
"""
Validator for validation choice field.
"""
message = 'Value must be one of `{allowed_values}`.'
def __init__(self, choices, *args, **kwargs):
"""
Validator for validation choice field.
:param Union[iter, dict] choices: Valid choices values.
"""
try:
iter(choices)
except TypeError:
raise ValueError('`choices=` must be iter or dict. Reality: `{}`.'.format(type(choices)))
super().__init__(*args, **kwargs)
self.choices = choices
def __call__(self, value: object):
"""
Validation.
:param object value: Object for validation.
"""
if value not in self.choices:
raise ValidationError(self.message.format(**dict(allowed_values=self.choices)))