Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 72 ยท Forms and User Input

Validating Input Without Libraries

Validate Flask form input with plain Python. Build reusable check functions, collect errors in a dict, re-render forms with the user's input and flash success.

Libraries such as Flask-WTF are convenient, but validating by hand is worth learning for two reasons. It shows you exactly what a validation library does, and for a small form or a JSON endpoint it is often the simplest solution, with no dependency at all. The rules are always the same: never trust input, check every field, collect all problems instead of stopping at the first, and give the user a form that still contains what they typed.

In this lesson you will write a clean validation function, return its errors in a dictionary, re-render the form with messages and the old values, and finish a successful submission with a flash message. You should already know how to read request.form from handling HTML forms.

Clean first, then check

Validation really has two jobs: cleaning (trim spaces, convert strings to numbers, normalize case) and checking (is the value acceptable?). Do the cleaning first, so the checks see tidy values. A good pattern is a function that takes the raw form data and returns two things: the cleaned values and a dictionary of errors keyed by field name.

Python A validation function that collects every error

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.

Notice what the function does not do: it never raises on bad input and never returns at the first failure. Every field is checked, so the user sees all problems at once instead of fixing them one per round trip. The age field shows the standard "optional number" trick: empty means no value (None), anything else must parse and fall in range. An if/elif chain per field means a field carries at most one message, the most important one.

Checks like the regular expressions above are a first filter, not proof. An email regex cannot know if the mailbox exists; the only real test is sending a message. Keep patterns simple, and see regular expressions if you want to refine them.

Validation in the browser (required, type="email", minlength) is a nicety for honest users and gives instant feedback. It is not security. Anyone can send a request without a browser, so the server must always repeat every check.

Showing errors and keeping the input

When validation fails, send the form back with three things: an error message next to each field, the values the user typed (so they do not retype everything), and a suitable status code. Use 400 Bad Request or 422 Unprocessable Content for invalid submissions, rather than 200, so that tests, proxies and scripts can tell the difference. Browsers display the body either way.

Never put the password back into the form. Leave password fields empty on every re-render.

flowchart TD
    P["POST arrives"] --> C["Clean the raw values"]
    C --> V["Check every field"]
    V --> Q{"errors empty?"}
    Q -->|no| R["Re-render the form<br/>with values and errors, status 422"]
    Q -->|yes| S["Save data"]
    S --> F["flash a success message"]
    F --> G["Redirect (303) to a GET page"]

Invalid input stays on the form page; valid input finishes with a redirect, as in Post/Redirect/Get.

Python A complete sign-up view with 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.

In the first failure the username input keeps its (escaped) value, &lt;al&gt;, because Jinja's autoescaping turns the user's angle brackets into harmless text; see Jinja basics. Two errors appear at once, the status is 422, and the password box is empty. The last request shows a business rule check (uniqueness) alongside format checks. In a real application, the uniqueness check would query the database, and you should still handle the race where two people register the same name at the same moment, for example by catching the database's unique-constraint error as well.

Reusing checks with small validators

As forms multiply, you will repeat the same rules. Turn each rule into a small function that returns an error message or None, then describe each field as a list of rules. This is essentially what WTForms does, built in a dozen lines:

Python Composable rules

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.

Each field stops at its first failing rule (the break), so a blank title says "required" rather than also complaining about its length. Keep schemas close to the view that uses them, or in a forms.py module, and share rules that appear everywhere. When the schema grows complicated, a library earns its keep; Flask-WTF and, for JSON, the tools in validation and serialization are the next step.

Flash messages for success and notices

After a successful save, the user should get feedback such as "Profile updated". Because success ends with a redirect, you cannot pass the message to the next template as a variable. Flask's flash messages solve this: flash("text", "category") stores a message in the session, and the next request reads it once with get_flashed_messages(), after which it is gone. Flashing needs SECRET_KEY, because the session is a signed cookie. The next lesson is dedicated to flash messages; here is the minimum:

Python Flash after a successful redirect

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.

Two behaviors are visible here. A message flashed on a request that renders the page directly (the failing case) is shown in that same response. A message flashed before a redirect appears on the next page, once. The final GET shows no message, because flashed messages are removed from the session after they are read. Categories like error and success let your template pick styles.

A checklist for hand-written validation

  • Clean (strip, lower-case where it makes sense, convert types) before you check.
  • Check every field and return all errors together, keyed by field name.
  • Treat missing keys as empty strings with .get(name, "").
  • Re-render with the user's values, but never a password; use status 400 or 422.
  • Escape on output (Jinja does this for you) and use parameterized queries when you store the data.
  • On success, save, flash, and redirect.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why collect all errors in a dict instead of returning at the first one?

    Showing all problems at once is friendlier. A dict keyed by field name also makes it easy to place each message next to its input.
  2. 2. A form with invalid data is re-rendered. Which status code is a good choice?

    A client error status tells browsers, tests and scripts that the submission was rejected. 422 Unprocessable Content and 400 Bad Request are both common.
  3. 3. Does HTML required or type="email" make server-side validation unnecessary?

    Browser validation is a usability feature. Anyone can send crafted requests directly to your URL.
  4. 4. Where does flash('Saved', 'success') store the message until the next request?

    Flashed messages live in the session, so SECRET_KEY must be set. get_flashed_messages() reads and clears them.
  5. 5. Why should the password field be left empty when the form is re-rendered with errors?

    Sending a secret back to the browser needlessly spreads it. Ask the user to retype it.

Summary

  • Validation = cleaning (strip, convert) + checking, returning (cleaned, errors) with errors keyed by field name.
  • Check every field and report all problems; never trust browser-side validation alone.
  • On errors, re-render the form with messages and the user's previous input (not the password) and a 400/422 status.
  • On success, save, flash() a message and redirect with 303 so a reload does not resubmit.
  • Small rule functions compose into schemas; reach for WTForms when forms get large.

Next: dive into flash messages, including categories and how the session carries them.