Open antonstakhouski opened 6 months ago
WTForms assumes that passed in data is already valid. So you should only expect to be able to validate formdata
. After all it's a forms library, not a general purpose validation library.
The Optional
/InputRequired
validators generally should also be first in the validation chain. I think the reason that Optional
clears errors is to avoid processing errors from surfacing to the application if the field was left empty, leaving the form in a faulty state where it can't be submitted. It unfortunately as a side-effect also hides incorrect validation chains. Generally it's weird that Optional
is a validator to begin with, it really should've been a field attribute, considering it doesn't even work correctly with all fields. The issue is even more apparent with DataRequired
.
If you want general purpose data validation then use something like pydantic. It should also be fairly easy to auto-generate a Form
based on a pydantic Model
and vice versa.
Your change will break existing code. You can always create your own internal validator, if you want to use WTForms this way, although I'd highly recommend against it.
If the form was filled with an object (like in REST scenario),
Optional
validator always raisesStopValidation
because it checksfield.raw_data
(and not thefield.data
) which will be always empty.Actual Behavior
Expected Behavior
Possible fix
If
field.raw_data
will be replaced withfield.data
, validation works as expected. But I don't know if this fix will break something in other places.Environment