forked from django-extensions/django-extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidators.py
66 lines (55 loc) · 2.06 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
# -*- coding: utf-8 -*-
import unicodedata
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
@deconstructible
class NoControlCharactersValidator(object):
message = _("Control Characters like new lines or tabs are not allowed.")
code = "no_control_characters"
whitelist = None
def __init__(self, message=None, code=None, whitelist=None):
if message:
self.message = message
if code:
self.code = code
if whitelist:
self.whitelist = whitelist
def __call__(self, value):
value = force_text(value)
whitelist = self.whitelist
category = unicodedata.category
for character in value:
if whitelist and character in whitelist:
continue
if category(character)[0] == "C":
params = {'value': value, 'whitelist': whitelist}
raise ValidationError(self.message, code=self.code, params=params)
def __eq__(self, other):
return (
isinstance(other, NoControlCharactersValidator) and
(self.whitelist == other.whitelist) and
(self.message == other.message) and
(self.code == other.code)
)
@deconstructible
class NoWhitespaceValidator(object):
message = _("Leading and Trailing whitespace is not allowed.")
code = "no_whitespace"
def __init__(self, message=None, code=None, whitelist=None):
if message:
self.message = message
if code:
self.code = code
def __call__(self, value):
value = force_text(value)
if value != value.strip():
params = {'value': value}
raise ValidationError(self.message, code=self.code, params=params)
def __eq__(self, other):
return (
isinstance(other, NoWhitespaceValidator) and
(self.message == other.message) and
(self.code == other.code)
)