-
Notifications
You must be signed in to change notification settings - Fork 28
/
validators.py
52 lines (40 loc) · 1.45 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
import re
from distutils.util import strtobool
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.utils import dateparse
validate_parameter = RegexValidator(
re.compile(r"^[-_\w=]+$", re.UNICODE),
message="Enter a valid HTTP parameter name.",
code="invalid",
)
def validate_path_re(value):
try:
re.compile(value)
except re.error as e:
raise ValidationError(
"Enter either a valid path or a regular expression to match a "
"path, without a URL scheme, query string, or fragment."
) from e
def validate_boolean(value):
message = "Enter one of 'on', 'off', 'true', 'false', etc."
try:
strtobool(value)
except ValueError:
# This was a string with an invalid boolean value
raise ValidationError(message)
except AttributeError:
# This was not a string
if not isinstance(value, (int, bool)):
raise ValidationError(message)
def validate_user(value):
UserModel = get_user_model()
try:
UserModel.objects.get(**{UserModel.USERNAME_FIELD: value})
except UserModel.DoesNotExist:
raise ValidationError("Enter the username of a valid user.")
def validate_date(value):
datetime = dateparse.parse_datetime(value)
if datetime is None:
raise ValidationError("Enter an ISO 8601 date representation.")