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
Custom Form Validators & Secure File Uploads0%
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
HomeTutorialsFlaskCustom Form Validators & Secure File Uploads
Flash Messaging System & User Feedback UI

Custom Form Validators & Secure File Uploads

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

While built-in WTForms validators handle common requirements (length, email format, non-empty checks), real-world web applications frequently require custom business validation (e.g., verifying database uniqueness, rejecting reserved usernames) and secure file upload handling.


1. Defining Custom Field Validators

In WTForms, custom validation methods can be attached to a form class following a strict naming convention: validate_<field_name>(self, field).

If the validation condition fails, raise a ValidationError from wtforms.validators:

1from flask_wtf import FlaskForm
2from wtforms import StringField, SubmitField
3from wtforms.validators import DataRequired, ValidationError
4 
5RESERVED_USERNAMES = {"admin", "root", "system", "moderator", "superuser"}
6 
7class UserProfileForm(FlaskForm):
8 username = StringField("Username", validators=[DataRequired()])
9 submit = SubmitField("Update Profile")
10 
11 # Custom validator for the 'username' field
12 def validate_username(self, field):
13 entered_username = field.data.strip().lower()
14
15 # Rule 1: Reject reserved system words
16 if entered_username in RESERVED_USERNAMES:
17 raise ValidationError("This username is reserved by the system. Please choose another.")
18
19 # Rule 2: Check database for duplicates (simulated check)
20 # existing_user = User.query.filter_by(username=entered_username).first()
21 # if existing_user and existing_user.id != current_user.id:
22 # raise ValidationError("That username is already taken.")

2. Secure File Uploads with FileField & FileAllowed

Uploading files introduces severe security risks:

  • Malicious users uploading executable files (.exe, .php, .sh)
  • Path traversal attacks exploiting malicious filenames (../../etc/passwd)
  • Denial of service via massive file sizes

Flask-WTF provides FileField, FileRequired, and FileAllowed to enforce strict type whitelisting.

1pip install Flask-WTF[file]

3. Sanitizing Filenames with secure_filename

Never trust the client-provided file.filename. Always pass it through Werkzeug's secure_filename() to strip dangerous path separators and special characters:

1import os
2import uuid
3from flask import Flask, render_template, request, flash, redirect, url_for
4from werkzeug.utils import secure_filename
5from forms import AvatarUploadForm
6 
7app = Flask(__name__)
8app.config["SECRET_KEY"] = "secure-secret-key"
9app.config["UPLOAD_FOLDER"] = os.path.join(app.root_path, "static", "uploads", "avatars")
10app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024 # Max upload size: 5 Megabytes
11 
12os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)
13 
14@app.route("/upload-avatar", methods=["GET", "POST"])
15def upload_avatar():
16 form = AvatarUploadForm()
17
18 if form.validate_on_submit():
19 file = form.avatar.data
20
21 # 1. Sanitize the filename
22 original_filename = secure_filename(file.filename)
23
24 # 2. Prevent filename collisions by prefixing a unique UUID
25 ext = original_filename.rsplit(".", 1)[1].lower()
26 unique_filename = f"{uuid.uuid4().hex}.{ext}"
27
28 # 3. Save to disk
29 save_path = os.path.join(app.config["UPLOAD_FOLDER"], unique_filename)
30 file.save(save_path)
31
32 flash("Avatar successfully uploaded!", "success")
33 return redirect(url_for("profile"))
34
35 return render_template("upload_avatar.html", form=form)

Essential: Multipart Form Encoding

When building forms with file upload inputs, you must include enctype="multipart/form-data" on the <form> tag:

1<form method="POST" enctype="multipart/form-data">
2 {{ form.hidden_tag() }}
3
4 <div class="mb-4">
5 {{ form.avatar.label }}
6 {{ form.avatar(class="form-input") }}
7 {% for error in form.avatar.errors %}
8 <p class="text-red-500 text-xs">{{ error }}</p>
9 {% endfor %}
10 </div>
11
12 {{ form.submit(class="btn btn-primary") }}
13</form>

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What naming convention does WTForms require for in-form custom field validation methods?
Question 2
What exception must be raised when a custom validation rule fails?
Question 3
What security vulnerability does Werkzeug's secure_filename() prevent?
Question 4
What HTML attribute is required on a <form> element when uploading files?
Question 5
What application configuration setting limits the maximum permitted upload payload size in Flask?
Next Lesson

Flash Messaging System & User Feedback UI

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

Related Lessons

Previous LessonNext Lesson
Form Classes & Built-In Field ValidatorsFlash Messaging System & User Feedback UI

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