dnmgmt/whoisdb/validators.py

41 lines
1.1 KiB
Python

from django.core import validators
from django.core.exceptions import ValidationError
from django.utils import six
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
import re
import ipaddress
@deconstructible
class HandleValidator(validators.RegexValidator):
regex = r'^(?:[A-Z]+[0-9]*(-[A-Z]+)|AUTO)'
message = _(
'Enter a valid handle (all uppercase)'
)
flags = re.ASCII if six.PY3 else 0
@deconstructible
class HandleValidatorWithSuffix(validators.RegexValidator):
flags = re.ASCII if six.PY3 else 0
def __init__(self, suffix):
self.regex = r'^(?:[A-Z]+[0-9]*-%s|AUTO)' % re.escape(suffix)
self.message = _(
'Enter a valid handle with suffix %s (all uppercase), e.g. FOO3-%s' % (suffix, suffix)
)
super(HandleValidatorWithSuffix, self).__init__()
def IP46CIDRValidator(value):
if not re.match(r"[0-9a-fA-F:.]+/[0-9]+", value):
raise ValidationError("Address needs to be a subnet in the format of ip/prefix")
try:
ipaddress.ip_network(value)
except ValueError as e:
raise ValidationError(str(e))