Wafflekonez
Wafflekonez

Reputation: 29

Is there a way to validate that one checkbox is checked in Flask?

I am trying to create a Flask Form that include multiple checkboxes. However, I want to make sure that the user has at least one checkbox checked out of a group of about 30 checkboxes. Is it possible to do in Flask?

This is the Python Code for 3 of the buttons

button1 = BooleanField('button1')
button2 = BooleanField('button2')
button3 = BooleanField('button3')

This is the Jinja2 code for 3 of the buttons

{{ form.button1(class="form-checkbox-input") }}
{{ form.button1.label(class="form-check-label") }}<br>
{{ form.button2(class="form-checkbox-input") }}
{{ form.button2.label(class="form-check-label") }}<br>
{{ form.button3(class="form-checkbox-input") }}
{{ form.button3.label(class="form-check-label") }}<br>

Upvotes: 1

Views: 1071

Answers (1)

paxdiablo
paxdiablo

Reputation: 881133

button1 = BooleanField('button1')
button2 = BooleanField('button2')
button3 = BooleanField('button3')

This is a rather inefficient (in the sense of what you have to write, not speed of your code) way to handle arrays. You might want to consider using an actual array, something like(a):

buttonArray = []
for idx in range(30):
    # F-strings relatively recent Python, you could go back
    # to "button%d".format(idx + 1) if need be.

    buttonArray.append(BooleanField(f'button{idx + 1}'))

Then you could just use this to check if one or more is true:

if any(buttonArray):
    atLeastOneTrue()

and something like this to process each true element:

for idx in range(len(buttonArray)):
    if buttonArray[idx]:
        print(f'button{idx + 1} is true')

(a) Keep in mind I have very little knowledge of Jinja2 but it wouldn't surprise me if you could make them arrays at that point to make it even more efficient.

Upvotes: 1

Related Questions