How to validate form data in python flask applications

lets start our tutorial , When you’re building a web application using Flask, it’s essential to ensure that the data users submit through forms is both correct and safe. Without validating user input, you might end up with incomplete, incorrect, or even malicious data entering your system, which could cause bugs or security issues.

Luckily, Flask makes it easy to handle form data validation. It provides built-in ways to check if the user has filled out required fields, if their email looks valid, and more. In this guide, we’ll go through the basics of validating form data in Flask, focusing on ensuring that a user’s name and email are both valid before processing the form.

validating the form data

For example, if a user submits a form but leaves the name or email blank, Flask can let them know that these fields are required. You can also check if the email they entered looks like a proper email address by ensuring it contains an “@” symbol.

In this guide, we’ll look at how to check the form data and give users helpful feedback if something’s wrong. By the end of this, you’ll understand how to ensure your forms are both user-friendly and secure.

now let’s see Flask form validation code

  • Python Flask Code
from flask import Flask, render_template, request, redirect, url_for, flash

app = Flask(__name__)
app.secret_key = 'secret'  # Flash messages require a secret key

@app.route('/')
def home():
    return render_template('form.html')

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    email = request.form['email']

    if not name:
        flash('Name is required!')
        return redirect(url_for('home'))
    
    if '@' not in email:
        flash('Invalid email!')
        return redirect(url_for('home'))

    flash('Form submitted successfully!')
    return redirect(url_for('home'))

if __name__ == '__main__':
    app.run(debug=True)
  • HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Submit Form</title>
</head>
<body>
    <h2>Submit Your Information</h2>

    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <ul>
                {% for message in messages %}
                    <li>{{ message }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endwith %}

    <form action="/submit" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br><br>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

now lets see some example output  cases :

Example Output cases :

Example 1 : Correct submission

Let’s say the user enters a valid name and a valid email.

Form Input:

Flask Behaviour :

  • The Flask application will check:

  1. Name: It’s not empty, so it passes
  2. Email: It contains the @ symbol, so it passes.

Output :

The user will see a success message: "Form submitted successfully!"

Example 2 : Missing Name

Let’s say the user submits the form without entering a name.

Form Input:

Flask Behaviour :

  • The Flask application will check:

    1. Name: It’s empty, so it will trigger an error message: “Name is required!”

    2. Email: It contains @, so it would pass if the name was entered.

Output :

The user will see an error message: "Name is required!"

 

Example 3 : Invalid Email

Now, let’s see what happens when the user submits an invalid email.

Form Input:

  • Name: basha

  • Email: basha.com (missing @)

Flask Behaviour :

  • The Flask application will check:

    1. Name: It’s not empty, so it passes.

    2. Email: It doesn’t contain @, so it will trigger an error message: “Invalid email!”

Output :

The user will see an error message: "Invalid email!"

Example 4 : Both Name and Email are Invalid

Let’s consider the case where both fields are incorrectly filled.

Form Input:

  • Name: (left blank)

  • Email: basha.com (missing @)

Flask Behaviour :

  • The Flask application will check:

    1. Name: It’s empty, so it triggers the “Name is required!” message.

    2. Email: It’s missing @, so it triggers the “Invalid email!” message.

Output :

  • The user will see two error messages:
    1. "Name is required!"
    2. "Invalid email!"
      
      
      
      
      

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top