How to validate a DateField in WTForms
Asked Answered
M

1

5

In my flask app I have a WTForm with two date pickers for a 'start date' and an 'end date'. What is the best way to validate that the 'end date' is not earlier than the 'start date'?

from flask_wtf import FlaskForm
from wtforms.fields.html5 import DateField
from wtforms import SubmitField 

class Form(FlaskForm):
    startdate_field = DateField('Start Date', format='%Y-%m-%d')
    enddate_field = DateField('End Date', format='%Y-%m-%d')
    submit_field = SubmitField('Simulate')

The only thing I found on this topic was this validator:

 wtforms_html5.DateRange

Found here: https://pypi.org/project/wtforms-html5/0.1.3/ but it seems to be an old version of wtforms-html5.

Macdougall answered 17/5, 2019 at 11:16 Comment(2)
Does this answer help?Pyongyang
The linked answer did not work for me. It raised an error because it tried to compare the two dates before the fields were populated.Macdougall
M
17

I figured it out. In the form class one can define a method validate_{fieldname} that validates the corresponding field. This method takes as arguments field and form so I can refer to the startdate field as form.startdate_field. Here is the code:

from flask_wtf import FlaskForm
from wtforms import SubmitField
from wtforms.validators import ValidationError
from wtforms.fields.html5 import DateField

class Form(FlaskForm):
    startdate_field = DateField('Start Date', format='%Y-%m-%d')
    enddate_field = DateField('End Date', format='%Y-%m-%d')
    submit_field = SubmitField('Next')

    def validate_enddate_field(form, field):
        if field.data < form.startdate_field.data:
            raise ValidationError("End date must not be earlier than start date.")
Macdougall answered 22/5, 2019 at 14:46 Comment(1)
The best answer to this question, it still works in 2022. Thank you!Panama

© 2022 - 2024 — McMap. All rights reserved.