Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 72 ยท Forms and User Input

Validation with WTForms

Define forms as Python classes with Flask-WTF and WTForms. Add validators, custom checks, CSRF protection, render fields and errors, and test with the client.

Reading request.form by hand works for a contact form, but a sign-up page with ten fields quickly turns into a pile of if statements: is the field present, long enough, a number in range, the same as another field? And you must also remember to protect every form against cross-site request forgery. WTForms is a library that turns this into a declarative style. You describe a form as a Python class, listing its fields and rules, and the library validates the submission, converts the types and collects the error messages. Flask-WTF connects WTForms to Flask and adds CSRF protection.

This lesson builds a registration form step by step. If you have not yet handled forms the plain way, read handling HTML forms first, and compare with validating without libraries.

Installing, and a stand-in

At home you install the extension with pip install flask-wtf; it brings wtforms with it. In the browser editors the examples call micropip.install for the same packages. The first example below uses no library at all: it is a small stand-in that shows the idea behind WTForms, so you understand what the library does for you.

Python The idea behind a form class (plain Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

That is the whole pattern: each field remembers its data and errors, validators are small functions, and the form's validate() runs them all. WTForms does the same with many more field types, ready-made validators, HTML rendering and an extra safety layer. Now the real thing.

Your first FlaskForm

Define a class that inherits from FlaskForm. Each field is a class attribute: the type decides how the raw string is converted, the first argument is the label, and validators is a list of rules. Flask-WTF forms need a SECRET_KEY (used to sign the CSRF token); this example switches CSRF off to focus on validation, and the next section turns it back on.

Python Fields, validators and form.errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the first run. Every field that broke a rule has a list of messages in form.errors. The age field shows the numeric range message, confirm reports the mismatch, and the unchecked box reports the custom message you supplied. In the second run, the form is valid and age is the integer 36, not the string "36", and terms is True. The Optional() validator on age means an empty value is acceptable and the remaining age rules are skipped.

Commonly used validators:

Validator Checks
DataRequired() The field has a truthy value (not empty, not unchecked)
InputRequired() Something was submitted, even 0
Optional() Empty is fine; stop validating if empty
Length(min, max) String length
NumberRange(min, max) Numeric range
Regexp(pattern) Matches a regular expression
EqualTo("other") Equals another field (password confirmation)
AnyOf([...]), NoneOf([...]) In or out of a list
URL() Looks like a URL
Email() Looks like an email (needs the email-validator package)

Common field types are StringField, PasswordField, TextAreaField, IntegerField, DecimalField, BooleanField, SelectField, RadioField, DateField and SubmitField. Use InputRequired for numbers where zero is a legitimate answer, because DataRequired treats 0 as empty.

Writing your own checks

Rules that belong to one field can be an inline validator: a method named validate_<fieldname> on the form. It receives the field and raises ValidationError to fail. For a reusable rule, write a function that takes (form, field) and put it in the validators list.

Python Inline and reusable custom validators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

SelectField also validates the choice: fr is not in the list, so the form rejects it with Not a valid choice. That protects you from tampered submissions, because the server never trusts the dropdown. Run order matters too: all field validators and the inline validate_username run, and the messages are collected together.

Rendering fields in a template

A field object is callable. {{ form.username() }} renders the <input>, {{ form.username.label }} renders the <label>, and extra keyword arguments become HTML attributes: {{ form.username(class_="input", placeholder="name") }} (use class_ because class is a Python keyword). Loop over field.errors to show messages. Put {{ form.hidden_tag() }} inside the <form> to render the CSRF token and any other hidden fields.

The view follows the same shape you saw in handling HTML forms: create the form, and if validate_on_submit() is true (the request is a POST and every validator passed), do the work and redirect; otherwise render the form again, now carrying the user's input and errors.

flowchart TD
    R["Request"] --> F["form = SignupForm()<br/>fills fields from request.form"]
    F --> Q{"POST and<br/>valid?"}
    Q -->|yes| S["Save data<br/>redirect (PRG)"]
    Q -->|"no (GET or errors)"| T["Render template<br/>with form and errors"]

validate_on_submit() is false for a GET and for an invalid POST, so both fall through to render the page.

CSRF protection

Cross-site request forgery tricks a logged-in user's browser into sending a request to your site from another site, for example a hidden form on a malicious page that posts to /delete-account. The browser attaches the user's cookies, so your app cannot tell the request was not intended. Flask-WTF defends by putting a secret, signed, per-session token into every form. A forged request cannot know the token, so it is rejected.

CSRF protection is on by default in FlaskForm. The token travels in a hidden field named csrf_token, which hidden_tag() renders. The example below uses the test client like a browser: it loads the page, reads the token and posts it back.

Python CSRF tokens, rendering and the full cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The forged request, which has no token, never reaches your saving code: validation fails with The CSRF token is missing. The signed token is also tied to the visitor's session, so a token copied from another user does not work. The token is random-looking and changes between runs, which is why the example prints only that it exists.

Some practical notes:

  • Always keep CSRF on in production. Switch it off only in tests, with WTF_CSRF_ENABLED = False in the test configuration (see testing Flask apps).
  • For JavaScript requests (fetch), send the token in an X-CSRFToken header; Flask-WTF's CSRFProtect(app) can protect all POST routes, not just those using forms.
  • The whole story, including cookies, XSS and SQL injection, continues in web security essentials.

What about file fields and complex forms?

WTForms also has FileField for uploads (Flask-WTF adds FileAllowed and FileRequired validators), FieldList and FormField for repeating or nested groups, and QuerySelectField-style helpers in some extensions. Uploads are covered in file uploads.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does form.validate_on_submit() return for an ordinary GET request?

    validate_on_submit() is true only when the request is a submission (POST, PUT, PATCH or DELETE) and all validators pass.
  2. 2. Why is IntegerField better than reading request.form['age'] yourself?

    The field processes the raw string into a Python int and adds a validation message for non-numeric input.
  3. 3. What is the purpose of {{ form.hidden_tag() }} in a template?

    hidden_tag() outputs the hidden inputs of the form, most importantly csrf_token.
  4. 4. A POST arrives without the CSRF token. What happens?

    The csrf_token field has its own validator. Without a valid token, validate_on_submit() returns False.
  5. 5. How do you write a validation rule that belongs to a single field called 'username' inside the form class?

    WTForms looks for methods named validate_<fieldname> and passes the field. Raise ValidationError to fail.

Summary

  • A FlaskForm subclass declares fields and validators; validate_on_submit() checks the request and the rules in one call.
  • Fields convert types (IntegerField, BooleanField), and form.errors maps field names to lists of messages.
  • Built-in validators cover required, length, range, regex, equality and choices; write validate_<field> methods or (form, field) functions for your own rules.
  • Render with form.field(), form.field.label and form.hidden_tag(); extra keyword arguments become HTML attributes.
  • CSRF tokens are on by default and signed with SECRET_KEY; turn them off only in tests.
  • The extension installs with pip install flask-wtf (and email-validator if you use Email()).

Prefer to understand every moving part? See how to do it all by hand in validating input without libraries.