Short Answer
Unless you have a good reason you should use InputRequired
Why?
Lets look at some notes from the docs/code for DataRequired()
:
Note there is a distinction between this and DataRequired in that InputRequired looks that form-input data was provided, and DataRequired looks at the post-coercion data.
and
NOTE this validator used to be called Required
but the way it behaved (requiring coerced data, not input data) meant it functioned in a way which was not symmetric to the Optional
validator and furthermore caused confusion with certain fields which coerced data to 'falsey' values like 0
, Decimal(0)
, time(0)
etc. Unless a very specific reason exists, we recommend using the :class: InputRequired
instead.
what does this mean?
In the Form
class you will notice two keyword arguments formdata
and data
. These generally correspond with two methods process
and process_formdata
. When form data comes in off the wire its not always in the format corresponding to the Field
type. A good example of this is the value u'1'
being supplied to an IntegerField
. This would be bad news if you had a NumberRange
validator because u'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
and DataRequired
work the same way specifically the __call__
implementations:
def __call__(self, form, field):
if not field.data or isinstance(field.data, string_types) and not field.data.strip():
if self.message is None:
message = field.gettext('This field is required.')
else:
message = self.message
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 apply DataRequired
to this it will fail validation. This is because DataRequired
will evaluate if not field.data...
after coercion where field.data
is the Falsey numeric value 0
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…