diff options
| author | Bobby <[email protected]> | 2022-11-27 12:07:34 -0500 |
|---|---|---|
| committer | Bobby <[email protected]> | 2022-11-27 12:07:34 -0500 |
| commit | f5cb8a4d14c48f458039d608f6bd38bea13a881c (patch) | |
| tree | 058eabbcdbca3bd98533e0130dc7e348a0ea460a /src | |
| parent | 3dfdd675e661f32f7373a521ad66ab56f637e0c4 (diff) | |
| download | edify-f5cb8a4d14c48f458039d608f6bd38bea13a881c.tar.xz edify-f5cb8a4d14c48f458039d608f6bd38bea13a881c.zip | |
added url validator
Diffstat (limited to 'src')
| -rw-r--r-- | src/edify/library/__init__.py | 1 | ||||
| -rw-r--r-- | src/edify/library/url.py | 38 |
2 files changed, 39 insertions, 0 deletions
diff --git a/src/edify/library/__init__.py b/src/edify/library/__init__.py index be1c093..16c5651 100644 --- a/src/edify/library/__init__.py +++ b/src/edify/library/__init__.py @@ -8,3 +8,4 @@ from .ip import ipv6 from .mail import email from .mail import email_rfc_5322 from .phone import phone_number +from .url import url diff --git a/src/edify/library/url.py b/src/edify/library/url.py new file mode 100644 index 0000000..532617e --- /dev/null +++ b/src/edify/library/url.py @@ -0,0 +1,38 @@ +import re + +proto = "^https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$" +no_proto = "^[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$" + +def url(url: str, match: list = ["proto", "no_proto"]) -> bool: + """Checks if a string is a valid URL. + + Args: + url (str): The string to check. + match (list): The protocols to match against. Defaults to ["https", "http", "no_proto"]. + Returns: + bool: True if the string is a valid URL, False otherwise. + """ + + # Validate match argument + if not isinstance(match, list): + raise TypeError("match argument must be a list") + + if not match: + raise ValueError("match argument must not be empty") + + # Validate protocols + protocols = [] + for protocol in match: + if protocol == "proto": + protocols.append(proto) + elif protocol == "no_proto": + protocols.append(no_proto) + else: + raise ValueError("Invalid protocol: {}".format(protocol)) + + # Check if URL matches any of the protocols + for protocol in protocols: + if re.match(protocol, url): + return True + + return False |
