0Pricing
Flask Academy · Lekcja

Własne walidatory i błędy pól

Pisz reguły i wyświetlaj użytkownikom komunikaty.

Własne walidatory i błędy pól to bezpłatna lekcja Flask Academy na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Flask Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Flask Academy zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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, Email

Inline 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. 🌟

Często zadawane pytania

Czy lekcja „Własne walidatory i błędy pól” jest bezpłatna?

Tak — pełny tekst „Własne walidatory i błędy pól” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Flask Academy, przejdź na CoddyKit PRO. Kurs Flask Academy zawiera 4 lekcji w sumie.

Co nauczysz się w „Własne walidatory i błędy pól”?

Pisz reguły i wyświetlaj użytkownikom komunikaty. Ćwiczysz Flask Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Flask Academy?

Nie wymagamy żadnego doświadczenia. Flask Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Własne walidatory i błędy pól”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Flask Academy?

Tak. Każda lekcja Flask Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Definiowanie klasy FlaskForm
  2. Renderowanie i wysyłanie formularza
  3. validate_on_submit i tokeny CSRF
  4. Własne walidatory i błędy pól
← Powrót do Flask Academy