Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Length Validator passing None when min=0 #873

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/wtforms/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,11 @@ def __init__(self, min=-1, max=-1, message=None):
self.field_flags["maxlength"] = self.max

def __call__(self, form, field):
length = field.data and len(field.data) or 0
if field.data is None:
length = -1
else:
length = len(field.data)

if length >= self.min and (self.max == -1 or length <= self.max):
return

Expand Down
33 changes: 33 additions & 0 deletions tests/validators/test_length.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,36 @@ def test_length_messages(dummy_form, dummy_field, validator, message):
validator(dummy_form, dummy_field)

assert message in str(e.value)


@pytest.mark.parametrize("min_v, max_v", [(-1, 5)])
def test_null_str_pass(min_v, max_v, dummy_form, dummy_field):
"""
The null string (field not in submitted formdata, thus field.data is None)
should pass when min=-1, ie no minimum required.
"""
dummy_field.data = None
validator = length(min_v, max_v)
validator(dummy_form, dummy_field)


@pytest.mark.parametrize("min_v, max_v", [(0, 5), (0, -1)])
def test_null_str_fail(min_v, max_v, dummy_form, dummy_field):
"""
The null string (field not in submitted formdata, thus field.data is None)
should fail when min=0
"""
dummy_field.data = None
validator = length(min_v, max_v)
with pytest.raises(ValidationError):
validator(dummy_form, dummy_field)


@pytest.mark.parametrize("min_v, max_v", [(0, 5), (0, -1)])
def test_empty_str_pass(min_v, max_v, dummy_form, dummy_field):
"""
The empty string ('') should pass when min=0
"""
dummy_field.data = ""
validator = length(min_v, max_v)
validator(dummy_form, dummy_field)
Loading