[英]WTForms custom field validation doesn't execute
Following this answer: How to validate a DateField in WTForms I attempted to make a custom validation.按照这个答案: How to validate a DateField in WTForms我试图进行自定义验证。 But it doesn't get called.
但它不会被调用。 I know this because the
ValidationError
doesn't happen during testing.我知道这一点是因为在测试期间不会发生
ValidationError
。
import datetime as dt
from flask_wtf import FlaskForm
from wtforms import SubmitField, DateTimeField
from wtforms.validators import ValidationError
class NotificationMessage(FlaskForm):
expire = DateTimeField(
'Expire',
default=dt.datetime.today() + dt.timedelta(days=31),
validators=[],
format='%Y-%m-%d %H:%M')
submit = SubmitField('Send Notification')
def validate_expire(form, field):
# if field.data and field.data < dt.datetime.today():
raise ValidationError('Expire datetime must be in the future.')
Must I call the validate_expire
method explicitly in my flask route or something?我必须在我的 flask 路由中明确调用
validate_expire
方法吗?
Must I call the validate_expire method explicitly in my flask route or something?
我必须在我的 flask 路由中明确调用 validate_expire 方法吗?
No, but you have to call form.validate()
or form.validate_on_submit()
in your endpoint (the parentheses are important, otherwise you are just checking that these methods exist).不,但是您必须在端点中调用
form.validate()
或form.validate_on_submit()
(括号很重要,否则您只是在检查这些方法是否存在)。
Both functions are expecting ValidationErrors and are catching them and simply return a boolean.这两个函数都期待 ValidationErrors 并捕获它们并简单地返回一个布尔值。 No exception is raised in the application code.
应用程序代码中没有引发异常。
After calling one of the validation functions you can also check form.errors
for a dictionary of lists of errors per field.在调用其中一个验证函数后,您还可以检查
form.errors
以获取每个字段的错误列表字典。
Your form code works as expected.您的表单代码按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.