Form Validation (Flask)

Form validation in Flask checks that submitted data meets your rules before you act on it. With Flask-WTF you attach validators to fields and call validate_on_submit(); errors collect in form.errors for display.

Flask

Never trust user input. Validation enforces requirements like 'this field is required', 'must be a valid email', or 'password at least 8 characters' on the server, regardless of any client-side checks that an attacker could bypass.

WTForms validators are small callables attached per field: DataRequired(), Length(min=8), Email(), EqualTo('password') for confirm fields, and Regexp() for custom patterns. You can also write a validate_<fieldname> method on the form for custom logic, like checking a username is unique.

When validate_on_submit() returns False, each field's errors are populated, and {{ form.email.errors }} in the template lets you show them next to the offending input.

Syntax

if form.validate_on_submit():
    ...  # data is valid

Examples

Python

from wtforms import PasswordField, StringField
from wtforms.validators import DataRequired, Length, EqualTo

class RegForm(FlaskForm):
    pw = PasswordField(validators=[DataRequired(), Length(min=8)])
    confirm = PasswordField(validators=[EqualTo("pw")])

Learn it in a lesson

See also

Back to the Dictionary