사용자 지정 검증기와 필드 오류
규칙을 작성하고 사용자에게 메시지를 표시합니다.
사용자 지정 검증기와 필드 오류은(는) CoddyKit의 무료 Flask Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flask Academy 강의 전체를 잠금 해제할 수 있습니다. Flask Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“사용자 지정 검증기와 필드 오류”에서 뭘 배우나요?
규칙을 작성하고 사용자에게 메시지를 표시합니다. 브라우저에서 직접 실행하는 실습 코드로 Flask Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Flask Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Flask Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“사용자 지정 검증기와 필드 오류” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Flask Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Flask Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- FlaskForm 클래스 정의하기
- 양식 렌더링하고 제출하기
- validate_on_submit과 CSRF 토큰
- 사용자 지정 검증기와 필드 오류