A field that validates input as an URL.
| 181 | |
| 182 | |
| 183 | class URLField(StringField): |
| 184 | """A field that validates input as an URL.""" |
| 185 | |
| 186 | _URL_REGEX = LazyRegexCompiler( |
| 187 | r"^(?:[a-z0-9\.\-]*)://" # scheme is validated separately |
| 188 | r"(?:(?:[A-Z0-9](?:[A-Z0-9-_]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}(?<!-)\.?)|" # domain... |
| 189 | r"localhost|" # localhost... |
| 190 | r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|" # ...or ipv4 |
| 191 | r"\[?[A-F0-9]*:[A-F0-9:]+\]?)" # ...or ipv6 |
| 192 | r"(?::\d+)?" # optional port |
| 193 | r"(?:/?|[/?]\S+)$", |
| 194 | re.IGNORECASE, |
| 195 | ) |
| 196 | _URL_SCHEMES = ["http", "https", "ftp", "ftps"] |
| 197 | |
| 198 | def __init__(self, url_regex=None, schemes=None, **kwargs): |
| 199 | """ |
| 200 | :param url_regex: (optional) Overwrite the default regex used for validation |
| 201 | :param schemes: (optional) Overwrite the default URL schemes that are allowed |
| 202 | :param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.StringField` |
| 203 | """ |
| 204 | self.url_regex = url_regex or self._URL_REGEX |
| 205 | self.schemes = schemes or self._URL_SCHEMES |
| 206 | super().__init__(**kwargs) |
| 207 | |
| 208 | def validate(self, value): |
| 209 | # Check first if the scheme is valid |
| 210 | scheme = value.split("://")[0].lower() |
| 211 | if scheme not in self.schemes: |
| 212 | self.error(f"Invalid scheme {scheme} in URL: {value}") |
| 213 | |
| 214 | # Then check full URL |
| 215 | if not self.url_regex.match(value): |
| 216 | self.error(f"Invalid URL: {value}") |
| 217 | |
| 218 | |
| 219 | class EmailField(StringField): |
no test coverage detected
searching dependent graphs…