One of the biggest reasons why we would choose WTForms over HTML Forms is the built-in validation. Instead of us having to write our own validation code e.g. emails should contain a "@" and a "." to be valid or make sure that passwords are minimum of 8 characters, we can use all these validation rules straight out of the box from WTForms.
1. We can add validator objects when we create each field in our form. e.g.
The validators
parameter accepts a List of validator Objects. DataRequired makes the two fields required fields, so the user must type something, otherwise an error will be generated.
When a form is submitted, there may be a number of errors, so a List of errors
can be generated and passed over to our form HTML as a property on the field which generated the error, e.g.
form.<field>.errors
2. We can tap into these errors and loop through them to show some text when an error appears.
3. The final step is to tell our form to validate the user's entry when they hit submit. so we have to edit our route and make sure it is able to respond to POST
requests and then to validate_on_submit()
.
If you tried to test your form at the moment, you will see that if you leave a field empty, it might give you a pop-up e.g. on Chrome:
This behaviour is not from our validator, in fact it's a built-in mechanism that varies from browser to browser. You'll see something different on Firefox or Safari. But If your user is running Internet Explorer, they won't see any validation.
4. In order to make sure that we are giving all users field validation, we have to switch off the browser validation, and we do that with an attribute on the form element called novalidate
.
Now test your validation, it should give you a warning in red if you leave any field empty and click "Log In". e.g.
CHALLENGE: Using the documentation on WTForm validators, add Email
validation to the email field so that you must type a valid email (with "@" and ".") otherwise you get an error. Also add Length
validation to the password, so you must type at least 8 characters.
e.g. Email without "@" and 4 character password:
Hint: Pay close attention if the documentation mentions anything about installing an additional package to get email validation to work. If so, you may want to pip install that package through the Terminal.