What is difference between DataRequired
and InputRequired
in wtforms.valiadators
I have some fields in my signup form :
username
password
password_repeat
submit
Should these fields use the DataRequired
or InputRequired
validator?
What is difference between DataRequired
and InputRequired
in wtforms.valiadators
I have some fields in my signup form :
username
password
password_repeat
submit
Should these fields use the DataRequired
or InputRequired
validator?
Short Answer
Unless you have a good reason you should use
InputRequired
Why?
Lets look at some notes from the docs/code:
and
what does this mean?
In the
Form
class you will notice two keyword argumentsformdata
anddata
. These generally correspond with two methodsprocess
andprocess_formdata
. When form data comes in off the wire its not always in the format corresponding to theField
type. A good example of this is the valueu'1'
being supplied to anIntegerField
. This would be bad news if you had aNumberRange
validator becauseu'1'
isn't a number.The primary purpose of the
process_formdata
method is to prevent this situation by coercing the value into its correct type prior to running validation rules. That is what they are referring to when they say "looks at the post-coercion data"the problem!
Both
InputRequired
andDataRequired
work the same way specifically the__call__
implementations:Certain field types coerce data into Falsey values(0, Decimal(0), etc.). The problem occurs when you have an
IntegerField
and the form submits a value like'0'
. If you applyDataRequired
to this it will fail validation. This is becauseDataRequired
will evaluateif not field.data...
after coercion wherefield.data
is the Falsey numeric value0
.