From ac63687a48e2d16540fc71724a0ad68bf3ed3556 Mon Sep 17 00:00:00 2001 From: Ross Crawford-d'Heureuse Date: Mon, 7 Apr 2025 10:41:45 +1000 Subject: [PATCH] fix: 307 class variable for pattern and updated regexp added tests --- pydantic_extra_types/domain.py | 5 +++-- tests/test_domain.py | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/pydantic_extra_types/domain.py b/pydantic_extra_types/domain.py index 6640de6..b772979 100644 --- a/pydantic_extra_types/domain.py +++ b/pydantic_extra_types/domain.py @@ -14,6 +14,8 @@ class DomainStr(str): """A string subclass with custom validation for domain string format.""" + _domain_re_pattern = r'(?=^.{1,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(? str: """Validate a domain name from the provided value. @@ -37,8 +39,7 @@ def _validate(cls, v: Any) -> DomainStr: if len(v) < 1 or len(v) > 253: raise PydanticCustomError('domain_length', 'Domain must be between 1 and 253 characters') - pattern = r'^([a-z0-9-]+(\.[a-z0-9-]+)+)$' - if not re.match(pattern, v): + if not re.match(cls._domain_re_pattern, v): raise PydanticCustomError('domain_format', 'Invalid domain format') return cls(v) diff --git a/tests/test_domain.py b/tests/test_domain.py index a149b94..77e6e1a 100644 --- a/tests/test_domain.py +++ b/tests/test_domain.py @@ -27,6 +27,8 @@ class MyModel(BaseModel): 'exam ple.com', # Space in domain 'exa_mple.com', # Underscore in domain 'example.com.', # Trailing dot + '192.168.1.23', # Ip address + '192.168.1.0/23', # CIDR ] very_long_domains = [