Skip to content
New issue

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

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

Already on GitHub? # to your account

#606 Make SelectMultipleField respect validate_choice #642

Merged
Merged
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
5 changes: 4 additions & 1 deletion src/wtforms/fields/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,10 @@ def process_formdata(self, valuelist):
)

def pre_validate(self, form):
if self.data:
if self.choices is None:
raise TypeError(self.gettext("Choices cannot be None."))

if self.validate_choice and self.data:
values = list(c[0] for c in self.choices)
for d in self.data:
if d not in values:
Expand Down
23 changes: 23 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,29 @@ def test_empty_choice(self, choices):
form = F(a="bar")
assert form.a() == '<select id="a" multiple name="a"></select>'

def test_validate_choices_when_empty(self):
F = make_form(a=SelectMultipleField(choices=[]))
form = F(DummyPostData(a=["b"]))
assert not form.validate()
assert form.a.data == ["b"]
assert len(form.a.errors) == 1
assert form.a.errors[0] == "'b' is not a valid choice for this field."

def test_validate_choices_when_none(self):
F = make_form(a=SelectMultipleField())
form = F(DummyPostData(a="b"))
with pytest.raises(TypeError, match="Choices cannot be None"):
form.validate()

def test_dont_validate_choices(self):
F = make_form(
a=SelectMultipleField(choices=[("a", "Foo")], validate_choice=False)
)
form = F(DummyPostData(a=["b"]))
assert form.validate()
assert form.a.data == ["b"]
assert len(form.a.errors) == 0


class TestRadioField:
class F(Form):
Expand Down