Introduction

Form validation is a crucial aspect of web development. It ensures that the data submitted by users through forms is accurate, complete, and secure. In this guide, we'll explore how to perform form validation in Flask, a Python web framework. By following this guide, you'll learn how to create and validate forms in your Flask applications to improve user experience and data integrity.


Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and installing the necessary extensions. Here's a sample directory structure:

form-validation-app/
app.py
templates/
index.html

Step 2: Creating a Form

Create an HTML form in a template (e.g., index.html). Here's a basic form structure:

<!DOCTYPE html>
<html>
<head>
<title>Form Validation Example</title>
</head>
<body>
<header>
<h1>Form Validation Example</h1>
</header>
<section>
<h2>Contact Information</h2>
<form method="post" action="/submit">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
</section>
</body>
</html>

Step 3: Handling Form Submission

Create a route in your Flask application to handle the form submission and perform validation. Here's an example route:

# app.py
from flask import Flask, render_template, request, redirect, url_for
from wtforms import Form, StringField, validators
app = Flask(__name)
class ContactForm(Form):
name = StringField('Name', [validators.InputRequired()])
email = StringField('Email', [validators.Email()])
@app.route('/')
def index():
form = ContactForm(request.form)
return render_template('index.html', form=form)
@app.route('/submit', methods=['POST'])
def submit():
form = ContactForm(request.form)
if form.validate():
name = form.name.data
email = form.email.data
# Process the data, e.g., store it in a database
return f"Form submitted: Name - {name}, Email - {email}"
else:
return "Form validation failed."
if __name__ == '__main__':
app.run(debug=True)

Step 4: Running Your Form Validation App

Run your Flask form validation application using the following command:

python app.py

Access your web application in a browser, and you'll be able to submit the form with validation in place.


Conclusion

Flask form validation is a fundamental skill for building web applications. By following the steps in this guide, you can set up your Flask application, create and validate forms, and ensure that user-submitted data is accurate and secure. You can enhance your form validation by adding more complex validation rules and custom error messages.