Validator personalizzati ed errori dei campi
Scriva regole e mostri i messaggi agli utenti.
Validator personalizzati ed errori dei campi è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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. 🌟
Domande Frequenti
La lezione «Validator personalizzati ed errori dei campi» è gratuita?
Sì — il testo completo di «Validator personalizzati ed errori dei campi» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.
Cosa imparerò in «Validator personalizzati ed errori dei campi»?
Scriva regole e mostri i messaggi agli utenti. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Flask Academy?
Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Validator personalizzati ed errori dei campi»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Flask Academy?
Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Definire una classe FlaskForm
- Renderizzare e inviare un form
- validate_on_submit e token CSRF
- Validator personalizzati ed errori dei campi