Custom Validators and Field Errors
Write rules and surface messages to users.
Custom Validators and Field Errors is a free Flask Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Flask Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Beyond Built-Ins
Built-in validators cover the basics, but real apps have unique rules. Now you will write custom validators and surface clear errors. ✍️
Recall the Standard Set
You already know DataRequired, Length, and Email. Custom rules layer on top of these for logic the library cannot guess.
from wtforms.validators import DataRequired, Length, EmailInline with validators
A custom validator is just a function in the field's validators list. It receives the form and the field on every check.
def not_admin(form, field):
pass
name = StringField('Name', validators=[not_admin])Raise ValidationError
To reject a value, raise ValidationError with a message. WTForms catches it and attaches the text to that field.
from wtforms.validators import ValidationError
def not_admin(form, field):
if field.data == 'admin':
raise ValidationError('Name is reserved.')The validate_ Convention
For a one-field rule, add a method named validate_fieldname on the form class. WTForms calls it automatically.
class SignupForm(FlaskForm):
username = StringField('Username')
def validate_username(self, field):
if len(field.data) < 3:
raise ValidationError('Too short.')Validate Against the Database
These methods can run any code, so check the database to reject a username that is already taken.
def validate_email(self, field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('Email already used.')Errors Land on the Field
Each failed message goes into field.errors, a simple list. An empty list means that field passed cleanly.
form.username.errors # ['Too short.']Show Errors in the Template
Loop over a field's errors in Jinja to display them. Users see exactly what to fix right beside the input.
{% for error in form.username.errors %}
<span class="err">{{ error }}</span>
{% endfor %}All Errors at Once
For a summary, use form.errors. It maps every field name to its list of messages after validation runs.
form.errors # {'username': ['Too short.']}Reusable Validator Classes
For rules you reuse, write a class with a __call__ method. Configure it once, then drop it into many fields.
class NoSpaces:
def __call__(self, form, field):
if ' ' in field.data:
raise ValidationError('No spaces allowed.')Keep Messages Helpful
Good error messages tell the user how to fix the problem, not just that something is wrong. Clarity builds trust.
Quick Check
How do you reject a value inside a custom validator function?
Recap
You added rules inline, via validate_fieldname methods, and reusable classes, raising ValidationError and showing messages from field.errors. 🌟
Frequently asked questions
Is the “Custom Validators and Field Errors” lesson free?
Yes — the full text of “Custom Validators and Field Errors” is free to read here on the web, and the Flask Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Flask Academy course, upgrade to CoddyKit PRO.
What will I learn in “Custom Validators and Field Errors”?
Write rules and surface messages to users. You practise Flask Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Flask Academy?
No prior experience is required. Flask Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Custom Validators and Field Errors” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Flask Academy lesson?
Yes. Every Flask Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Define a FlaskForm Class
- Render and Submit a Form
- validate_on_submit and CSRF Tokens
- Custom Validators and Field Errors