Be Careful With ColdFusion Date Validation

Published: {ts '2011-06-24 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/be-careful-with-coldfusion-date-validation/

It may sound odd but although I build a lot of forms, I rarely have problems with date validation. That is until today.

The way I used to handle dates was to supply 2 drop downs "day" "month" and a four character year field. This made date validation a snap. However I recently started making use of ColdFusion's datefield input type on my forms. This led me to forget rule number one.

Never Trust You Inputs

I should know better, but for whatever reason I relied on the client side validation to ensure a valid date was entered. However one user seems to have been able to get around it and submit an invalid date. Since I made the mistake of trusting the input the save process blew up.

After realizing my mistake I went in and put in server side validation, which subsequently failed to work.

isDate() Sucks

isDate() does exactly what it says on the box. You pass it a string and it tells you if it is a date or not. Unfortunately it is VERY permissive. It will accept anything that looks like a date/time and validate it as true. This combined with the inability to specify a format can cause big headache.

For example the following would all be validated as TRUE:

Enter isValid()

Like isDate(), isValid() allows you to validate a date. To do this specify isValid("date",yourdate) and you will get back a true/false value. This is essentially the same as isDate().

Unlike isDate() though you can be more specific. If you call isValid() specifying "USDate" as the format only US formatted dates will pass.

Demo

To demonstrate take this code and run it.

#isDate(date1)#
#isDate(date2)#
#isdate(date3)#
#isValid("date",date1)#
#isValid("date",date2)#
#isValid("date",date3)#
#isValid("USDate",date1)#
#isValid("USDate",date2)#
#isValid("USDate",date3)#

Conclusion

ColdFusion supplies some great functions to make life easier. However you need to pay attention as even the seemingly obvious functions can have pitfalls.