📖 Scenario: You are building a simple web form using Flask where users can submit their name and age. To ensure the data is correct, you need to add validation rules to the form fields.
🎯 Goal: Create a Flask app with a form that validates the user's name to be non-empty and the age to be a number between 1 and 120.
📋 What You'll Learn
Create a Flask app with a route for the form
Create a form class with fields name and age
Add validation rules: name must not be empty, age must be an integer between 1 and 120
Render the form in a template and show validation errors if any
💡 Why This Matters
🌍 Real World
Forms with validation are common in websites for user registration, surveys, and data collection.
💼 Career
Understanding form validation in Flask is essential for backend web development roles that handle user input securely and correctly.
Progress0 / 4 steps
1
Set up Flask app and form class
Create a Flask app instance called app and define a form class called UserForm that inherits from FlaskForm. Add two fields: name as a StringField and age as an IntegerField.
Flask
Hint
Import Flask, FlaskForm, StringField, and IntegerField. Create app and UserForm with the two fields.
2
Add validation rules to form fields
Add validators to the name and age fields in UserForm. Use DataRequired() for name to ensure it is not empty. Use NumberRange(min=1, max=120) for age to ensure it is between 1 and 120.
Flask
Hint
Import DataRequired and NumberRange from wtforms.validators. Add them inside the validators list for each field.
3
Create route to display and process the form
Create a route / with a function index that creates an instance of UserForm. If the form is submitted and valid, just return the string 'Form submitted'. Otherwise, render a template called form.html passing the form instance as form.
Flask
Hint
Use @app.route with methods=['GET', 'POST']. Inside the function, create form = UserForm(). Use form.validate_on_submit() to check if valid. Return the string or render the template accordingly.
4
Create the HTML template to show the form and errors
Create a template file form.html that displays the form fields name and age with their labels and input boxes. Show validation error messages below each field if present. Add a submit button labeled Submit. Use form.hidden_tag() for CSRF protection.
Flask
Hint
Use {{ form.hidden_tag() }} for CSRF. Show each field label and input. Loop over form.field.errors to show errors in red. Add a submit button.
Practice
(1/5)
1. What is the main purpose of validation rules in a Flask web application?
easy
A. To speed up the server response time
B. To style the web page with CSS
C. To check user input and ensure it meets expected criteria
D. To store data permanently in the database
Solution
Step 1: Understand validation rules
Validation rules are used to check if user input is correct and safe before processing.
Step 2: Identify the main purpose in Flask
In Flask, validation ensures data is valid and prevents errors or security issues.
Final Answer:
To check user input and ensure it meets expected criteria -> Option C
Quick Check:
Validation = Check input correctness [OK]
Hint: Validation means checking user input is correct [OK]
Common Mistakes:
Confusing validation with styling or database storage
Thinking validation speeds up server response
Ignoring the role of validation in input safety
2. Which of the following is the correct way to import the DataRequired validator from WTForms in a Flask app?
easy
A. import DataRequired from wtforms.fields
B. import DataRequired from flask
C. from flask_wtf import DataRequired
D. from wtforms.validators import DataRequired
Solution
Step 1: Identify the correct module for validators
WTForms validators are imported from the wtforms.validators module.
Step 2: Check the import syntax
The correct syntax is 'from wtforms.validators import DataRequired'.
Final Answer:
from wtforms.validators import DataRequired -> Option D
Quick Check:
Validator import = from wtforms.validators [OK]
Hint: Validators come from wtforms.validators module [OK]
Common Mistakes:
Importing from flask or flask_wtf incorrectly
Using wrong import syntax
Confusing fields with validators
3. Given this Flask-WTF form code snippet:
class MyForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) age = IntegerField('Age', validators=[NumberRange(min=18, max=99)])
What happens if a user submits the form with an empty name and age 17?
medium
A. Form validation fails with errors for both name and age fields
B. Form validation passes because age is a number
C. Form validation fails only for the name field
D. Form validation passes with no errors
Solution
Step 1: Check the name field validation
Name uses DataRequired(), so empty input causes validation failure.
Step 2: Check the age field validation
Age must be between 18 and 99; 17 is below minimum, so validation fails.
Final Answer:
Form validation fails with errors for both name and age fields -> Option A
Quick Check:
Empty name + age 17 = two validation errors [OK]
Hint: Check all validators; both fields fail here [OK]
Common Mistakes:
Assuming age 17 passes because it is a number
Ignoring DataRequired on name
Thinking only one field can fail
4. Consider this Flask-WTF form snippet:
class EmailForm(FlaskForm): email = StringField('Email', validators=[Email(), DataRequired()])
Why might this code cause a runtime error when validating?
medium
A. The Email validator is not imported, causing a NameError
B. DataRequired must come before Email in the validators list
C. StringField cannot have multiple validators
D. FlaskForm must be imported from flask, not flask_wtf
Solution
Step 1: Check imports for validators
If Email validator is not imported from wtforms.validators, it causes NameError at runtime.
Step 2: Validate other options
Order of validators does not cause error; multiple validators are allowed; FlaskForm import is correct from flask_wtf.
Final Answer:
The Email validator is not imported, causing a NameError -> Option A
Quick Check:
Missing import = NameError [OK]
Hint: Always import all validators used [OK]
Common Mistakes:
Thinking validator order matters for errors
Believing multiple validators are disallowed
Confusing FlaskForm import source
5. You want to create a Flask-WTF form that requires a username with at least 5 characters and a password that must be confirmed by retyping. Which validator combination correctly enforces these rules?