MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Form Classes & Built-In Field Validators0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
4.1Flask-WTF Setup & CSRF Token Protection4.2Form Classes & Built-In Field Validators4.3Custom Form Validators & Secure File Uploads4.4Flash Messaging System & User Feedback UI
HomeTutorialsFlaskForm Classes & Built-In Field Validators
Custom Form Validators & Secure File Uploads

Form Classes & Built-In Field Validators

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Manually writing <input> tags, extracting values from request.form, typecasting strings, and writing dozens of if not email: checks is tedious and error-prone. WTForms allows you to declare forms as Python classes, providing automatic validation, casting, and error aggregation.


1. Declaring a Form Class

Create a forms.py file and subclass flask_wtf.FlaskForm:

1from flask_wtf import FlaskForm
2from wtforms import (
3 StringField,
4 PasswordField,
5 BooleanField,
6 SubmitField,
7 SelectField,
8 TextAreaField
9)
10from wtforms.validators import (
11 DataRequired,
12 Length,
13 Email,
14 EqualTo,
15 Regexp
16)
17 
18class RegistrationForm(FlaskForm):
19 username = StringField(
20 label="Username",
21 validators=[
22 DataRequired(message="Username is required."),
23 Length(min=3, max=25, message="Username must be between 3 and 25 characters."),
24 Regexp(r'^[a-zA-Z0-9_]+$', message="Username must contain only letters, numbers, and underscores.")
25 ]
26 )
27
28 email = StringField(
29 label="Email Address",
30 validators=[
31 DataRequired(message="Email is required."),
32 Email(message="Please provide a valid email address.")
33 ]
34 )
35
36 password = PasswordField(
37 label="Password",
38 validators=[
39 DataRequired(),
40 Length(min=8, message="Password must be at least 8 characters long.")
41 ]
42 )
43
44 confirm_password = PasswordField(
45 label="Confirm Password",
46 validators=[
47 DataRequired(),
48 EqualTo("password", message="Passwords must match.")
49 ]
50 )
51
52 track = SelectField(
53 label="Specialization Track",
54 choices=[
55 ("fullstack", "Full-Stack Web Development"),
56 ("data_ai", "Data Science & AI"),
57 ("cloud", "Cloud & DevOps")
58 ],
59 validators=[DataRequired()]
60 )
61
62 terms = BooleanField(
63 label="I agree to the Terms of Service",
64 validators=[DataRequired(message="You must accept the terms.")]
65 )
66
67 submit = SubmitField(label="Create Account")

2. Handling Forms in the View Function

In your route, instantiate the form and call form.validate_on_submit():

1from flask import Flask, render_template, redirect, url_for, flash
2from forms import RegistrationForm
3 
4app = Flask(__name__)
5app.config["SECRET_KEY"] = "super-secret-key-change-in-production"
6 
7@app.route("/register", methods=["GET", "POST"])
8def register():
9 form = RegistrationForm()
10
11 # validate_on_submit() checks:
12 # 1. Is this an HTTP POST request?
13 # 2. Is the CSRF token valid?
14 # 3. Do all field validators pass?
15 if form.validate_on_submit():
16 user_name = form.username.data
17 user_email = form.email.data
18
19 # In a real app: save user to database with hashed password
20 flash(f"Account successfully created for {user_name}!", "success")
21 return redirect(url_for("login"))
22
23 # On GET request or failed validation, re-render form with errors
24 return render_template("register.html", form=form)

3. Rendering the Form in Jinja2

WTForms fields are callable objects. Invoking {{ form.field_name() }} generates the complete <input> HTML element:

1<!-- templates/register.html -->
2{% extends "base.html" %}
3 
4{% block content %}
5<div class="max-w-md mx-auto bg-white p-8 rounded-2xl shadow-sm border border-gray-100">
6 <h2 class="text-2xl font-bold mb-6 text-gray-900">Create Your Account</h2>
7
8 <form method="POST" action="">
9 <!-- Automatically renders hidden CSRF input token -->
10 {{ form.hidden_tag() }}
11
12 <!-- Username Field -->
13 <div class="mb-4">
14 {{ form.username.label(class="block text-sm font-medium text-gray-700 mb-1") }}
15 {{ form.username(class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500", placeholder="johndoe") }}
16 {% for error in form.username.errors %}
17 <p class="text-red-500 text-xs mt-1">{{ error }}</p>
18 {% endfor %}
19 </div>
20
21 <!-- Email Field -->
22 <div class="mb-4">
23 {{ form.email.label(class="block text-sm font-medium text-gray-700 mb-1") }}
24 {{ form.email(class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500", placeholder="you@example.com") }}
25 {% for error in form.email.errors %}
26 <p class="text-red-500 text-xs mt-1">{{ error }}</p>
27 {% endfor %}
28 </div>
29 
30 <!-- Password Field -->
31 <div class="mb-4">
32 {{ form.password.label(class="block text-sm font-medium text-gray-700 mb-1") }}
33 {{ form.password(class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500") }}
34 {% for error in form.password.errors %}
35 <p class="text-red-500 text-xs mt-1">{{ error }}</p>
36 {% endfor %}
37 </div>
38
39 <!-- Submit Button -->
40 <div class="mt-6">
41 {{ form.submit(class="w-full py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white font-bold rounded-lg cursor-pointer transition") }}
42 </div>
43 </form>
44</div>
45{% endblock %}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What three checks does form.validate_on_submit() execute automatically?
Question 2
How is the hidden CSRF input field rendered in templates when using FlaskForm?
Question 3
Which validator guarantees that two password fields match during registration?
Question 4
How do you extract the sanitized, type-converted value of a field inside a view function?
Question 5
How are validation errors accessed for an individual field in a Jinja2 template?
Next Lesson

Custom Form Validators & Secure File Uploads

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Flask-WTF Setup & CSRF Token ProtectionCustom Form Validators & Secure File Uploads

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext