From b86c6256d29418c35ca6e4b849756776da0b9227 Mon Sep 17 00:00:00 2001 From: andreas loeffler Date: Sun, 13 Nov 2022 20:08:45 +0100 Subject: [PATCH 1/2] for Regexp validator set html input tag 'pattern' attribute (used if novalidate not set on a form) test that pattern shows up in the input field --- src/wtforms/validators.py | 1 + tests/validators/test_regexp.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/wtforms/validators.py b/src/wtforms/validators.py index 86337c99f..35ec77fdc 100644 --- a/src/wtforms/validators.py +++ b/src/wtforms/validators.py @@ -341,6 +341,7 @@ def __init__(self, regex, flags=0, message=None): regex = re.compile(regex, flags) self.regex = regex self.message = message + self.field_flags = {"pattern": regex.pattern} def __call__(self, form, field, message=None): match = self.regex.match(field.data or "") diff --git a/tests/validators/test_regexp.py b/tests/validators/test_regexp.py index 6d89857cd..72e0bf4b5 100644 --- a/tests/validators/test_regexp.py +++ b/tests/validators/test_regexp.py @@ -48,6 +48,15 @@ def test_regex_raises(re_pattern, re_flags, test_v, dummy_form, dummy_field): validator(dummy_form, dummy_field) +def test_regexp_message_default(dummy_form, dummy_field, grab_error_message): + """ + Regexp validator should return default message + """ + validator = regexp("^a") + dummy_field.data = "f" + assert grab_error_message(validator, dummy_form, dummy_field) == "Invalid input." + + def test_regexp_message(dummy_form, dummy_field, grab_error_message): """ Regexp validator should return given message @@ -55,3 +64,13 @@ def test_regexp_message(dummy_form, dummy_field, grab_error_message): validator = regexp("^a", message="foo") dummy_field.data = "f" assert grab_error_message(validator, dummy_form, dummy_field) == "foo" + + +def test_regexp_pattern_html(dummy_form, dummy_field): + """ + Regexp validator should return given message + """ + validator = regexp("^[a-zA-Z0-9]+$") + dummy_field.data = "foo bar" + + assert validator.field_flags == {"pattern": '^[a-zA-Z0-9]+$'} From e49f2f2ae78a50ee1600f7879800a508816b996b Mon Sep 17 00:00:00 2001 From: andreas loeffler Date: Sun, 13 Nov 2022 21:51:42 +0100 Subject: [PATCH 2/2] replace quotes --- tests/validators/test_regexp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/validators/test_regexp.py b/tests/validators/test_regexp.py index 72e0bf4b5..935f8f57d 100644 --- a/tests/validators/test_regexp.py +++ b/tests/validators/test_regexp.py @@ -73,4 +73,4 @@ def test_regexp_pattern_html(dummy_form, dummy_field): validator = regexp("^[a-zA-Z0-9]+$") dummy_field.data = "foo bar" - assert validator.field_flags == {"pattern": '^[a-zA-Z0-9]+$'} + assert validator.field_flags == {"pattern": "^[a-zA-Z0-9]+$"}