Skip to content

Commit

Permalink
for Regexp validator set html input tag 'pattern' attribute (used if …
Browse files Browse the repository at this point in the history
…novalidate not set on a form)

test that pattern shows up in the input field
  • Loading branch information
lefty01 committed Nov 13, 2022
1 parent aa4e043 commit b86c625
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/wtforms/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "")
Expand Down
19 changes: 19 additions & 0 deletions tests/validators/test_regexp.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,29 @@ 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
"""
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]+$'}

0 comments on commit b86c625

Please sign in to comment.