Bird
Raised Fist0
Flaskframework~30 mins

Validation rules in Flask - Mini Project: Build & Apply

Choose your learning style10 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
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

  1. Step 1: Understand validation rules

    Validation rules are used to check if user input is correct and safe before processing.
  2. Step 2: Identify the main purpose in Flask

    In Flask, validation ensures data is valid and prevents errors or security issues.
  3. Final Answer:

    To check user input and ensure it meets expected criteria -> Option C
  4. 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

  1. Step 1: Identify the correct module for validators

    WTForms validators are imported from the wtforms.validators module.
  2. Step 2: Check the import syntax

    The correct syntax is 'from wtforms.validators import DataRequired'.
  3. Final Answer:

    from wtforms.validators import DataRequired -> Option D
  4. 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

  1. Step 1: Check the name field validation

    Name uses DataRequired(), so empty input causes validation failure.
  2. Step 2: Check the age field validation

    Age must be between 18 and 99; 17 is below minimum, so validation fails.
  3. Final Answer:

    Form validation fails with errors for both name and age fields -> Option A
  4. 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

  1. Step 1: Check imports for validators

    If Email validator is not imported from wtforms.validators, it causes NameError at runtime.
  2. Step 2: Validate other options

    Order of validators does not cause error; multiple validators are allowed; FlaskForm import is correct from flask_wtf.
  3. Final Answer:

    The Email validator is not imported, causing a NameError -> Option A
  4. 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?
hard
A. username = StringField('Username', validators=[Length(max=5)])
password = PasswordField('Password', validators=[DataRequired()])
confirm = PasswordField('Confirm Password', validators=[EqualTo('password')])
B. username = StringField('Username', validators=[DataRequired(), Length(min=5)])
password = PasswordField('Password', validators=[DataRequired(), EqualTo('confirm', message='Passwords must match')])
confirm = PasswordField('Repeat Password')
C. username = StringField('Username', validators=[DataRequired(), Length(max=5)])
password = PasswordField('Password', validators=[EqualTo('confirm')])
confirm = PasswordField('Repeat Password', validators=[DataRequired()])
D. username = StringField('Username', validators=[DataRequired(), Length(min=5)])
password = PasswordField('Password')
confirm = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('confirm')])

Solution

  1. Step 1: Check username validators

    Username needs DataRequired and Length(min=5) to enforce minimum length.
  2. Step 2: Check password and confirmation validators

    Password field requires DataRequired and EqualTo('confirm') to match confirmation; confirm field is defined without validators.
  3. Step 3: Compare options

    username = StringField('Username', validators=[DataRequired(), Length(min=5)])
    password = PasswordField('Password', validators=[DataRequired(), EqualTo('confirm', message='Passwords must match')])
    confirm = PasswordField('Repeat Password') correctly uses Length(min=5) and EqualTo with matching field names and messages.
  4. Final Answer:

    username = StringField('Username', validators=[DataRequired(), Length(min=5)])
    password = PasswordField('Password', validators=[DataRequired(), EqualTo('confirm', message='Passwords must match')])
    confirm = PasswordField('Repeat Password')
    -> Option B
  5. Quick Check:

    Length(min=5) + EqualTo('confirm') = correct validation [OK]
Hint: Use Length(min=5) and EqualTo('confirm') for password confirmation [OK]
Common Mistakes:
  • Using Length(max=5) instead of min for username
  • Placing EqualTo on wrong field
  • Missing DataRequired on password
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard