Back to Python
2026-01-296 min read

JS Form Validation (Python Programming)

Learn JS Form Validation (Python Programming) step by step with clear examples and exercises.

Why This Matters

In web development, validating user inputs is crucial to ensure data integrity and prevent errors. While JavaScript is commonly used for form validation on the client-side, Python can also handle this task when working with server-side applications or APIs. In this lesson, we'll learn how to validate forms using Python and understand its advantages over JavaScript in certain scenarios.

Prerequisites

To follow along with this lesson, you should have a basic understanding of:

  1. Python programming language syntax (variables, functions, loops, and conditional statements)
  2. HTML form structure
  3. Basic knowledge of web development concepts such as requests, responses, and APIs

Core Concept

Python offers several libraries for handling forms and validating user inputs. In this lesson, we'll use Flask-WTF, a popular extension for the Flask web framework that integrates with the Werkzeug andWTForms libraries to provide an easy-to-use form validation system.

Installation

First, make sure you have Python and pip installed on your system. Then, create a new virtual environment and install Flask, Flask-WTF, and WTForms:

$ python -m venv my_project_env
$ source my_project_env/bin/activate
$ pip install flask flask-wtf wtforms

Creating a simple form

Create a new file called app.py and define a basic Flask application:

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Email

app = Flask(__name__)

class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
return f'Name: {form.name.data}, Email: {form.email.data}'
return render_template('index.html', form=form)

if __name__ == '__main__':
app.run(debug=True)

In the code above, we've created a simple Flask application with a single route (/) that renders an HTML template called index.html. We also defined a form class MyForm that includes fields for name and email, as well as validation rules using the DataRequired and Email validators.

Creating the HTML template

Create a new folder named templates in the same directory as your app.py, and create an index.html file inside it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
</head>
<body>
<form method="POST" action="/">
{{ form.csrf_token }}
{{ form.name.label }}<br>
{{ form.name(size=30) }}<br><br>
{{ form.email.label }}<br>
{{ form.email(size=30) }}<br><br>
{{ form.submit() }}
</form>
</body>
</html>

In the HTML template, we've included the CSRF token for security purposes and rendered our MyForm.

Testing the application

Run your Flask application with:

$ python app.py

Now navigate to http://127.0.0.1:5000/ in your web browser, and you should see the form we created. Try submitting the form with invalid inputs, and you'll notice that Flask-WTF validates the input automatically and prevents the server from processing incorrect data.

Worked Example

Let's create a more complex example where we validate multiple fields and handle user errors.

from flask import Flask, request, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, SubmitField
from wtforms.validators import DataRequired, NumberRange

app = Flask(__name__)

class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
age = IntegerField('Age', validators=[DataRequired(), NumberRange(min=18, max=99)])
salary = IntegerField('Salary', validators=[DataRequired(), NumberRange(min=25000, max=500000)])
submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
return f'Name: {form.name.data}, Age: {form.age.data}, Salary: {form.salary.data}'
return render_template('index.html', form=form, errors=form.errors)

if __name__ == '__main__':
app.run(debug=True)

In this example, we've created a more complex form with three fields (name, age, and salary), each with specific validation rules using the NumberRange validator. We also modified our HTML template to display error messages when there are invalid inputs:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation</title>
</head>
<body>
{% for msg in get_flashed_messages() %}
<div style="color: red;">{{ msg }}</div>
{% endfor %}
<form method="POST" action="/">
{{ form.csrf_token }}
{{ form.name.label }}<br>
{{ form.name(size=30) }}<br><br>
{{ form.age.label }}<br>
{{ form.age(size=5) }}<br><br>
{{ form.salary.label }}<br>
{{ form.salary(size=10) }}<br><br>
{{ form.submit() }}
</form>
</body>
</html>

Now, when you run the application and submit invalid inputs, you'll see error messages displayed on the page to help users correct their mistakes.

Common Mistakes

  1. Not importing required libraries: Make sure you have flask, flask_wtf, and wtforms installed and imported in your Python script.
  2. Forgetting to render the CSRF token: The CSRF token is essential for security purposes, so make sure it's included in your HTML form.
  3. Not defining validation rules: If you don't define validation rules for your fields, they won't be validated automatically.
  4. Using incorrect field types: Make sure you use the appropriate field type (StringField, IntegerField, etc.) for each input.
  5. Not handling errors in the template: If you want to display error messages on the page, make sure your HTML template is set up to handle them properly.
  6. Missing form validation checks: Ensure that all necessary fields have validation rules defined, and that they cover all possible scenarios (e.g., minimum length, maximum length, format checks).

Practice Questions

  1. Create a form that validates a user's password (minimum of 8 characters, at least one uppercase letter, and at least one digit).
  2. Modify the example in this lesson to include a file upload field with a maximum file size of 5MB.
  3. Create a form for registering users that validates their username, email, and password according to the rules mentioned in question 1.
  4. Add a radio button group to the registration form that allows users to choose their gender (male or female). Make sure the input is properly validated.
  5. Modify the example in this lesson to include a dropdown list for selecting a user's country of residence, with validation to ensure the selected country exists in your database.

FAQ

  1. Why use Python for form validation instead of JavaScript?
  • Server-side validation ensures that even if a malicious user tries to manipulate the client-side code, their input will still be validated on the server before being processed or stored.
  • Python can handle more complex validations than JavaScript, such as database lookups and business rules.
  1. How do I handle multiple errors for a single field in Flask-WTF?
  • You can access all error messages for a specific field using the errors attribute of the form field object (e.g., form.name.errors).
  1. What if I want to validate user input on the client-side as well as the server-side?
  • You can use JavaScript for client-side validation, and Flask-WTF or another library for server-side validation. Make sure to handle both cases in your application.
  1. How do I customize error messages in Flask-WTF?
  • You can define custom error messages by creating a MessageFactory class that inherits from the base MessageFactory class provided by WTForms and overriding the methods for the specific validators you want to customize.
  1. Can I use Flask-WTF with other web frameworks besides Flask?
  • Yes, Flask-WTF can be used with other web frameworks that support WSGI applications, such as Pyramid and CherryPy. However, you may need to adapt the integration slightly depending on the specific framework.
JS Form Validation (Python Programming) | Python | XQA Learn