カスタムバリデーターとフィールドエラー
ルールを書き、ユーザーにメッセージを表示します
「カスタムバリデーターとフィールドエラー」はCoddyKit上の無料Flask Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはFlask Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Flask Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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. 🌟
よくある質問
「カスタムバリデーターとフィールドエラー」レッスンは無料ですか?
はい。「カスタムバリデーターとフィールドエラー」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Flask Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Flask Academyコースには全4レッスンが含まれています。
「カスタムバリデーターとフィールドエラー」で何を学びますか?
ルールを書き、ユーザーにメッセージを表示します ブラウザで直接実行するハンズオンコードでFlask Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Flask Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのFlask Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「カスタムバリデーターとフィールドエラー」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このFlask Academyレッスンでコードを書いて実行できますか?
はい。すべてのFlask Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- FlaskFormクラスを定義する
- フォームをレンダリングして送信する
- validate_on_submitとCSRFトークン
- カスタムバリデーターとフィールドエラー