2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
import re
|
2012-07-20 21:36:52 +08:00
|
|
|
try:
|
|
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
except ImportError: # Python 2
|
|
|
|
from urlparse import urlsplit, urlunsplit
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2012-08-30 04:40:51 +08:00
|
|
|
from django.utils.encoding import force_text
|
2011-06-11 21:48:24 +08:00
|
|
|
from django.utils.ipv6 import is_valid_ipv6_address
|
2012-07-20 20:22:00 +08:00
|
|
|
from django.utils import six
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
# These values, if given to validate(), will trigger the self.required check.
|
|
|
|
EMPTY_VALUES = (None, '', [], (), {})
|
|
|
|
|
|
|
|
class RegexValidator(object):
|
|
|
|
regex = ''
|
2012-06-08 00:08:47 +08:00
|
|
|
message = _('Enter a valid value.')
|
2010-01-05 11:56:19 +08:00
|
|
|
code = 'invalid'
|
|
|
|
|
|
|
|
def __init__(self, regex=None, message=None, code=None):
|
|
|
|
if regex is not None:
|
|
|
|
self.regex = regex
|
|
|
|
if message is not None:
|
|
|
|
self.message = message
|
|
|
|
if code is not None:
|
|
|
|
self.code = code
|
|
|
|
|
2011-06-10 07:51:03 +08:00
|
|
|
# Compile the regex if it was not passed pre-compiled.
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(self.regex, six.string_types):
|
2011-06-10 07:51:03 +08:00
|
|
|
self.regex = re.compile(self.regex)
|
2010-05-10 20:40:54 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def __call__(self, value):
|
|
|
|
"""
|
|
|
|
Validates that the input matches the regular expression.
|
|
|
|
"""
|
2012-08-30 04:40:51 +08:00
|
|
|
if not self.regex.search(force_text(value)):
|
2010-01-05 11:56:19 +08:00
|
|
|
raise ValidationError(self.message, code=self.code)
|
|
|
|
|
|
|
|
class URLValidator(RegexValidator):
|
|
|
|
regex = re.compile(
|
2011-03-16 11:38:34 +08:00
|
|
|
r'^(?:http|ftp)s?://' # http:// or https://
|
2011-02-13 03:11:49 +08:00
|
|
|
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
|
2010-01-05 11:56:19 +08:00
|
|
|
r'localhost|' #localhost...
|
2012-08-18 19:00:52 +08:00
|
|
|
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
|
|
|
|
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
|
2010-01-05 11:56:19 +08:00
|
|
|
r'(?::\d+)?' # optional port
|
|
|
|
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
|
|
|
|
|
|
|
|
def __call__(self, value):
|
2010-02-22 07:44:35 +08:00
|
|
|
try:
|
|
|
|
super(URLValidator, self).__call__(value)
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2010-02-22 07:44:35 +08:00
|
|
|
# Trivial case failed. Try for possible IDN domain
|
|
|
|
if value:
|
2012-08-30 04:40:51 +08:00
|
|
|
value = force_text(value)
|
2012-07-20 21:36:52 +08:00
|
|
|
scheme, netloc, path, query, fragment = urlsplit(value)
|
2010-02-22 07:44:35 +08:00
|
|
|
try:
|
2012-08-12 04:44:42 +08:00
|
|
|
netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
|
2010-02-22 07:44:35 +08:00
|
|
|
except UnicodeError: # invalid domain part
|
|
|
|
raise e
|
2012-07-20 21:36:52 +08:00
|
|
|
url = urlunsplit((scheme, netloc, path, query, fragment))
|
2010-02-28 20:01:18 +08:00
|
|
|
super(URLValidator, self).__call__(url)
|
2010-02-22 07:44:35 +08:00
|
|
|
else:
|
|
|
|
raise
|
2010-02-28 20:01:18 +08:00
|
|
|
else:
|
|
|
|
url = value
|
2010-02-22 07:44:35 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def validate_integer(value):
|
|
|
|
try:
|
|
|
|
int(value)
|
2011-09-11 06:46:44 +08:00
|
|
|
except (ValueError, TypeError):
|
2010-01-05 11:56:19 +08:00
|
|
|
raise ValidationError('')
|
|
|
|
|
2010-02-22 07:44:35 +08:00
|
|
|
class EmailValidator(RegexValidator):
|
|
|
|
|
|
|
|
def __call__(self, value):
|
|
|
|
try:
|
|
|
|
super(EmailValidator, self).__call__(value)
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2010-02-22 07:44:35 +08:00
|
|
|
# Trivial case failed. Try for possible IDN domain-part
|
2012-06-08 00:08:47 +08:00
|
|
|
if value and '@' in value:
|
|
|
|
parts = value.split('@')
|
2010-02-22 07:44:35 +08:00
|
|
|
try:
|
2012-08-12 04:44:42 +08:00
|
|
|
parts[-1] = parts[-1].encode('idna').decode('ascii')
|
2010-02-22 07:44:35 +08:00
|
|
|
except UnicodeError:
|
|
|
|
raise e
|
2012-06-08 00:08:47 +08:00
|
|
|
super(EmailValidator, self).__call__('@'.join(parts))
|
2010-02-22 07:44:35 +08:00
|
|
|
else:
|
|
|
|
raise
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
email_re = re.compile(
|
|
|
|
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
|
2012-01-08 02:43:46 +08:00
|
|
|
# quoted-string, see also http://tools.ietf.org/html/rfc2822#section-3.2.5
|
|
|
|
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"'
|
2011-06-10 18:22:42 +08:00
|
|
|
r')@((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$)' # domain
|
|
|
|
r'|\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE) # literal form, ipv4 address (SMTP 4.1.3)
|
2012-06-08 00:08:47 +08:00
|
|
|
validate_email = EmailValidator(email_re, _('Enter a valid e-mail address.'), 'invalid')
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2012-08-16 03:07:48 +08:00
|
|
|
slug_re = re.compile(r'^[-a-zA-Z0-9_]+$')
|
2012-06-08 00:08:47 +08:00
|
|
|
validate_slug = RegexValidator(slug_re, _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."), 'invalid')
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
ipv4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
|
2012-06-08 00:08:47 +08:00
|
|
|
validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid')
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
def validate_ipv6_address(value):
|
|
|
|
if not is_valid_ipv6_address(value):
|
2012-06-08 00:08:47 +08:00
|
|
|
raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
|
2011-06-11 21:48:24 +08:00
|
|
|
|
|
|
|
def validate_ipv46_address(value):
|
|
|
|
try:
|
|
|
|
validate_ipv4_address(value)
|
|
|
|
except ValidationError:
|
|
|
|
try:
|
|
|
|
validate_ipv6_address(value)
|
|
|
|
except ValidationError:
|
2012-06-08 00:08:47 +08:00
|
|
|
raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
|
2011-06-11 21:48:24 +08:00
|
|
|
|
|
|
|
ip_address_validator_map = {
|
|
|
|
'both': ([validate_ipv46_address], _('Enter a valid IPv4 or IPv6 address.')),
|
|
|
|
'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')),
|
|
|
|
'ipv6': ([validate_ipv6_address], _('Enter a valid IPv6 address.')),
|
|
|
|
}
|
|
|
|
|
|
|
|
def ip_address_validators(protocol, unpack_ipv4):
|
|
|
|
"""
|
|
|
|
Depending on the given parameters returns the appropriate validators for
|
|
|
|
the GenericIPAddressField.
|
|
|
|
|
|
|
|
This code is here, because it is exactly the same for the model and the form field.
|
|
|
|
"""
|
|
|
|
if protocol != 'both' and unpack_ipv4:
|
|
|
|
raise ValueError(
|
|
|
|
"You can only use `unpack_ipv4` if `protocol` is set to 'both'")
|
|
|
|
try:
|
|
|
|
return ip_address_validator_map[protocol.lower()]
|
|
|
|
except KeyError:
|
|
|
|
raise ValueError("The protocol '%s' is unknown. Supported: %s"
|
2012-08-08 22:33:15 +08:00
|
|
|
% (protocol, list(ip_address_validator_map)))
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
comma_separated_int_list_re = re.compile('^[\d,]+$')
|
2012-06-08 00:08:47 +08:00
|
|
|
validate_comma_separated_integer_list = RegexValidator(comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid')
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
|
|
|
|
class BaseValidator(object):
|
|
|
|
compare = lambda self, a, b: a is not b
|
|
|
|
clean = lambda self, x: x
|
2012-06-08 00:08:47 +08:00
|
|
|
message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).')
|
2010-01-05 11:56:19 +08:00
|
|
|
code = 'limit_value'
|
|
|
|
|
|
|
|
def __init__(self, limit_value):
|
|
|
|
self.limit_value = limit_value
|
|
|
|
|
|
|
|
def __call__(self, value):
|
|
|
|
cleaned = self.clean(value)
|
|
|
|
params = {'limit_value': self.limit_value, 'show_value': cleaned}
|
|
|
|
if self.compare(cleaned, self.limit_value):
|
|
|
|
raise ValidationError(
|
|
|
|
self.message % params,
|
|
|
|
code=self.code,
|
|
|
|
params=params,
|
|
|
|
)
|
|
|
|
|
|
|
|
class MaxValueValidator(BaseValidator):
|
|
|
|
compare = lambda self, a, b: a > b
|
2012-06-08 00:08:47 +08:00
|
|
|
message = _('Ensure this value is less than or equal to %(limit_value)s.')
|
2010-01-05 11:56:19 +08:00
|
|
|
code = 'max_value'
|
|
|
|
|
|
|
|
class MinValueValidator(BaseValidator):
|
|
|
|
compare = lambda self, a, b: a < b
|
2012-06-08 00:08:47 +08:00
|
|
|
message = _('Ensure this value is greater than or equal to %(limit_value)s.')
|
2010-01-05 11:56:19 +08:00
|
|
|
code = 'min_value'
|
|
|
|
|
|
|
|
class MinLengthValidator(BaseValidator):
|
|
|
|
compare = lambda self, a, b: a < b
|
|
|
|
clean = lambda self, x: len(x)
|
2012-06-08 00:08:47 +08:00
|
|
|
message = _('Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).')
|
2010-01-05 11:56:19 +08:00
|
|
|
code = 'min_length'
|
|
|
|
|
|
|
|
class MaxLengthValidator(BaseValidator):
|
|
|
|
compare = lambda self, a, b: a > b
|
|
|
|
clean = lambda self, x: len(x)
|
2012-06-08 00:08:47 +08:00
|
|
|
message = _('Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).')
|
2010-01-05 11:56:19 +08:00
|
|
|
code = 'max_length'
|
|
|
|
|