Skip to content
Advertisement

MultiCheckbox Field Validation with Flask WTForms

I have a WTForm and I am trying to validate a custom multi-checkbox field,

JavaScript

When I set the required flag to true, every checkbox needs to be checked. I just need at least one checkbox to be selected.

When I don’t set the required flag, the native, and very elusive (is doesn’t appear in js, html, or css via developer tools), validation modal doesn’t appear, and ‘manually’ displaying errors is required with,

JavaScript

How do I validate this field properly? I.e. just check if at least one box is true, if not, show the native modal. I also receive '1', '2', '3', '5', '4' are not valid choices for this field. if I check all the boxes and submit the form. Why is that?

This is the “native modal” I mention.

The native modal I mention

Advertisement

Answer

You can’t control the native validation modal/popup using WTForms. You’ll have to use JavaScript, see here.

Should you want to avoid using JS, validation of the multiple select checkbox list with WTForms can be done using

JavaScript

Notice the coerce=int. This will cast the numeric strings into integers making the field’s data compatible with get_languages().

Remove the native validation by adding the attribute novalidate to your html element.

You can skip writing the error conditions for each field by looping through the form fields,

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement