Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.
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() 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:
- 01/31/2011 (US)
- 31/01/2011 (Euro)
- 01-31-2011 5:00PM
- 3:00PM (I really do not understand how a time can be validated as a date)
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.
To demonstrate take this code and run it.
<cfset date1 = "50/1/1">
<cfset date2 = "05/02/11">
<cfset date3 = "31/5/11">
<!--- These will all pass --->
<!--- Again these will all pass --->
<!--- Only the second will pass --->
ColdFusion supplies some great functions to make life easier. However you need to pay attention as even the seemingly obvious functions can have pitfalls.