Tony Landis home

FormEncode - Validate Date is on Today or in the Future

Here is a simple validator I wrote for to check that the input is a valid date, and is >= today.

If you want to use YYYY-MM-DD date formatting instead, just edit the string in line 6 to '%Y-%m-%d'. You will also want to change the error text on line 11.

 1 import datetime, formencode
 2 
 3 class DateTodayOrFuture(formencode.FancyValidator):
 4  def _to_python(self, value, state):
 5          try:
 6                  val = datetime.date.strptime(str(value), '%m/%d/%Y')
 7          except ValueError:
 8                  val = None
 9          if not val:
10                  raise formencode.Invalid(\
11                          'This date is invalid, it must be mm/dd/yyyy', value, state)
12          else:
13                  if date(val.year, val.month, val.day) < datetime.date.today():
14                          raise formencode.Invalid(\
15                                  'The date must be on or after today', value, state)
16          return value