From 4971a9afe5642569f3dcfcd3972ebb39e88dd457 Mon Sep 17 00:00:00 2001 From: Berker Peksag Date: Tue, 27 Sep 2016 04:59:48 +0300 Subject: [PATCH] Fixed #18119 -- Added a DomainNameValidator validator. Thanks Claude Paroz for the review. Co-authored-by: Nina Menezes <77671865+nmenezes0@users.noreply.github.com> --- django/core/validators.py | 76 +++++++++++++++++++++++++++++++-------- docs/ref/validators.txt | 28 +++++++++++++++ docs/releases/5.1.txt | 5 ++- tests/validators/tests.py | 56 +++++++++++++++++++++++++++++ 4 files changed, 150 insertions(+), 15 deletions(-) diff --git a/django/core/validators.py b/django/core/validators.py index 57940a59dab..b1c5c053b84 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -65,6 +65,64 @@ class RegexValidator: ) +@deconstructible +class DomainNameValidator(RegexValidator): + message = _("Enter a valid domain name.") + ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string). + # Host patterns. + hostname_re = ( + r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?" + ) + # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1. + domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(? self.max_length: + raise ValidationError(self.message, code=self.code, params={"value": value}) + if not self.accept_idna and not value.isascii(): + raise ValidationError(self.message, code=self.code, params={"value": value}) + super().__call__(value) + + +validate_domain_name = DomainNameValidator() + + @deconstructible class URLValidator(RegexValidator): ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string). @@ -76,20 +134,10 @@ class URLValidator(RegexValidator): ) ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later) - # Host patterns - hostname_re = ( - r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?" - ) - # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1 - domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?