Skip to content

Commit 22b0c51

Browse files
committed
add url
1 parent 4c3e2b2 commit 22b0c51

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from pyvalueobjects.abstract.nullablevalueobject import build_nullable
2+
from pyvalueobjects.security.url import Url
3+
4+
_nullable_cls = build_nullable(Url)
5+
6+
7+
class NullableUrl(_nullable_cls):
8+
9+
def __init__(self, value: str = None):
10+
super().__init__(value)

pyvalueobjects/security/url.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import re
2+
3+
from pyvalueobjects.errors.ValueObjectError import ValueObjectError
4+
from pyvalueobjects.strings.non_empty_string import NonEmptyString
5+
6+
7+
class Url(NonEmptyString):
8+
9+
__MATCHER = re.compile(
10+
r'^(?:http[s]?://)?' # http:// or https:// (optional)
11+
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
12+
r'localhost|' # localhost...
13+
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
14+
r'(?::\d+)?' # optional port
15+
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
16+
17+
def __init__(self, value: str):
18+
super().__init__(value)
19+
20+
def _validate(self, value: str):
21+
super()._validate(value)
22+
try:
23+
is_correct = Url.__MATCHER.match(value)
24+
if not is_correct:
25+
raise ValueObjectError('Value must be a valid URL format (e.g. https://example.com or http://localhost:8080).')
26+
except ValueError:
27+
raise ValueObjectError('Value must be a valid URL format (e.g. https://example.com or http://localhost:8080).')

0 commit comments

Comments
 (0)