diff options
Diffstat (limited to 'webmentions_ssg/forms/validators.py')
| -rw-r--r-- | webmentions_ssg/forms/validators.py | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/webmentions_ssg/forms/validators.py b/webmentions_ssg/forms/validators.py index 2ce2b5b..36f36ce 100644 --- a/webmentions_ssg/forms/validators.py +++ b/webmentions_ssg/forms/validators.py @@ -14,6 +14,32 @@ from wtforms.form import BaseForm from ..url_security import AddressResolutionError, is_public_url +class URLMaxBytes: + """Check the UTF-8 byte length of a submitted URL using the current config.""" + + def __init__( + self, config_key: str = "MAX_WEBMENTION_URL_BYTES", message: str | None = None + ) -> None: + self.config_key = config_key + self.message = message + + def __call__(self, form: BaseForm, field: Field) -> None: + if field.data is None: + return + + max_bytes = current_app.config[self.config_key] + + try: + length = len(field.data.encode("utf-8")) + except UnicodeEncodeError as exc: + raise ValidationError(field.gettext("URL must be valid UTF-8.")) from exc + + if length > max_bytes: + raise ValidationError( + self.message or field.gettext(f"URL must not exceed {max_bytes} bytes.") + ) + + class NotEqualTo: """ Validate that a field does not equal another field. |
