how to implement not-required DateField using Flask-WTF

peon picture peon · Jan 4, 2015 · Viewed 15.2k times · Source

I want a DateField which is optional, but I got a "Not a valid date value" error if leave it empty

I add some logs in the source code of wtforms, and found formdata.getlist(self.name) returns [u''] for this DateField

The code of my form:

from wtforms import BooleanField, TextField, TextAreaField, PasswordField, validators, HiddenField, DateField, SelectField
from flask_wtf import Form

class EmployeeForm(Form):
    id = HiddenField('id')
    title = TextField('Title')
    start = DateField('Start Date', format='%m/%d/%Y')

Answer

dirn picture dirn · Jan 4, 2015

You are looking for the Optional validator.

start = DateField('Start Date', format='%m/%d/%Y', validators=(validators.Optional(),))