Form Validation and Data and Error Handling with Flask-WTF
In this lesson, we will learn how to validate the data received from the form and how to handle these validation errors.
Form validation
The Flask-WTF
forms provide us with some helpful functions that make the task of distinguishing between a GET
or POST
request easier. Let us discuss them below.
form.is_submitted()
This function is inherited from the WTForms
module. It returns true if all the fields of a form have been completely filled by the user. Otherwise, it returns false. This function does not check the validity of the data entered. It only checks whether all the fields of the form have been filled or not. For example, let’s suppose we have two text fields: Email
and Password
. form.is_submitted
will return true if both fields have been filled by the user. It does not matter whether the user enters the correct or incorrect email and password. However, if one or both fields are empty, then form.is_submitted
will return false.
form.validate()
This function is also inherited from the WTForms
module. It returns true if all the conditions specified in the validators have been met. For example, if we have a Email()
validator for the email
field and if the given input is not a valid email address, form.validate()
will return false.
form.validate_on_submit()
This function is a shortcut function that Flask-WTF
contains. It returns true if both form.is_submitted()
and form.validate()
return true.
Get hands-on with 1400+ tech skills courses.