How to Validate Form in Flask: Simple Guide with Example
To validate a form in Flask, use the
Flask-WTF extension which integrates WTForms for easy form handling and validation. Define a form class with fields and validators, then check form.validate_on_submit() in your route to process valid data.Syntax
Use Flask-WTF to create a form class by inheriting from FlaskForm. Define fields like StringField with validators such as DataRequired(). In your Flask route, instantiate the form and call form.validate_on_submit() to check if the form data is valid and submitted.
python
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired class MyForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) submit = SubmitField('Submit') # In Flask route: # form = MyForm() # if form.validate_on_submit(): # # process valid data # else: # # show form with errors
Example
This example shows a simple Flask app with a form that asks for a name. It validates that the name is not empty and displays a success message when the form is submitted correctly.
python
from flask import Flask, render_template_string, flash from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired app = Flask(__name__) app.secret_key = 'secret-key' class NameForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): flash(f'Hello, {form.name.data}! Your form is valid.') return render_template_string(''' <form method="POST"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name(size=20) }}<br> {% for error in form.name.errors %} <span style="color: red;">{{ error }}</span><br> {% endfor %} {{ form.submit() }} </form> {% with messages = get_flashed_messages() %} {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} ''', form=form) if __name__ == '__main__': app.run(debug=True)
Output
A web page with a form labeled 'Name' and a submit button. If submitted empty, it shows a red error 'This field is required.' If a name is entered, it shows 'Hello, [name]! Your form is valid.' below the form.
Common Pitfalls
- Not setting
SECRET_KEYin Flask app causes CSRF validation to fail. - Forgetting to include
{{ form.hidden_tag() }}in the template breaks CSRF protection. - Using
request.formdirectly instead ofform.validate_on_submit()skips validation. - Not adding validators like
DataRequired()means fields can be empty without errors.
python
from flask import Flask, render_template_string from flask_wtf import FlaskForm from wtforms import StringField, SubmitField app = Flask(__name__) app.secret_key = 'secret-key' class BadForm(FlaskForm): name = StringField('Name') # Missing DataRequired validator submit = SubmitField('Submit') @app.route('/bad', methods=['GET', 'POST']) def bad(): form = BadForm() if form.validate_on_submit(): return f'Hello, {form.name.data}!' return render_template_string(''' <form method="POST"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name(size=20) }}<br> {{ form.submit() }} </form> ''', form=form) # Correct way adds DataRequired validator to name field.
Quick Reference
- Define form: Create a class inheriting
FlaskFormwith fields and validators. - Validate form: Use
form.validate_on_submit()in route to check submission and validity. - CSRF protection: Set
app.secret_keyand include{{ form.hidden_tag() }}in templates. - Show errors: Loop over
form.field.errorsin template to display validation messages.
Key Takeaways
Use Flask-WTF and WTForms to handle form validation cleanly in Flask.
Always set a secret key and include CSRF token with hidden_tag() for security.
Call form.validate_on_submit() to check if form data is valid and submitted.
Add validators like DataRequired() to enforce input rules on fields.
Display validation errors in your template to guide users.