问题
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?
回答1:
Short Answer
Unless you have a good reason you should use InputRequired
Why?
Lets look at some notes from the docs/code:
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 theOptional
validator and furthermore caused confusion with certain fields which coerced data to 'falsey' values like0
,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
.
来源:https://stackoverflow.com/questions/23982917/flask-wtforms-difference-between-datarequired-and-inputrequired