'How to change priority of WTForms validators?
tl;dr: I need to change the order in which WTForms validators validate the user input. How do I do that?
Details:
Flask code:
class SampleForm(Form):
user_email = user_email_field
...
@api.route('/sample-route')
class ClassName(Resource):
@api.expect(sample_payload)
@api.marshal_with(sample_response)
def post(self):
form = SampleForm(formdata=MultiDict(api.payload))
if not form.validate():
return {"form_errors": form.errors}, 400
...
WTForms validation field:
user_email_field = EmailField('Email Address',[
validators.InputRequired(Errors.REQUIRED_FIELD),
validators.Length(min=5, max=256),
validators.Email(Errors.INVALID_EMAIL_ADDRESS),
])
Problem is, user_email is checked by validators in the wrong order. I send a request with the following body:
{
"user_email": ""
}
I get this response:
{
"form_errors": {
"user_email": [
"'' is too short"
]
}
}
As you see, despite being 2nd in the list of validators, validators.Length() kicks in before everything else.
If I comment it out in the validation field like that:
user_email_field = EmailField('Email Address',[
validators.InputRequired(Errors.REQUIRED_FIELD),
# validators.Length(min=5, max=256),
validators.Email(Errors.INVALID_EMAIL_ADDRESS),
])
then the exact same request will yield a desired response:
{
"errors": null,
"success": null,
"form_errors": {
"user_email": [
"REQUIRED_FIELD"
]
}
}
However, this is not a working solution because, of course, then eMail won't be checked for its length.
Question:
How do I change the priority of these validators? How do I make WTForms always check the user input with validators.InputRequired() FIRST and with validators.Length() SECOND and not the other way around?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
