0
0
Flaskframework~30 mins

Validation rules in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Flask Form Validation Rules
📖 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
Need a 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
Need a 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
Need a 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
Need a 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.