简体   繁体   中英

WTForms custom field validation doesn't execute

Following this answer: How to validate a DateField in WTForms I attempted to make a custom validation. But it doesn't get called. I know this because the ValidationError doesn't happen during testing.

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?

Must I call the validate_expire method explicitly in my flask route or something?

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).

Both functions are expecting ValidationErrors and are catching them and simply return a boolean. 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.

Your form code works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM