« Don't break the web? | ColdFusion spellchecker plugin for TinyMCE 3.0 »

February 21, 2008

ColdFusion IsDate() gotcha

I must be a slow learner because I've been bitten by the following gotcha in the ColdFusion IsDate() function more than once. So I'm writing this here mostly for my own sake, but it may be of value to others also.

I've used IsDate() many times in form validation logic to verify that a user entered a valid date into an HTML field. Usually, I need to verify that the input is something like 02/21/2008 or 2-21-08, and this function has saved me from writing a regular expression to validate the correct format.

But it turns out that IsDate() is pretty liberal in it's definition of a "date". According to the ColdFusion documentation, IsDate() returns true "if [the] string can be converted to a date/time value." This means that the following strings are all considered valid dates according to this function:

  • 02/21/2008
  • 2-21-08
  • 21/02/2008
  • 4:03
  • 4:03 pm
  • 21-02-08 4:03pm

It's the dd/mm/yyyy format that's caused me trouble before. If I'm expecting a date in mm/dd/yyyy format and IsDate() allows the user to enter 21/02/2008 then strange things start happening in my applications.

My solution is to replace IsDate() with IsValid("USdate", string_value) which will only return true if the string is a valid date in the mm/dd/yy format (with 1-2 digit days and months and 1-4 digit years).

Posted at 3:49 PM in ColdFusion

Comments

1. barry.b says:

"It's the dd/mm/yyyy format that's caused me trouble before."

funny ... for us, it's the mm/dd/yyyy format that some U.S developers try and "encourage" onto the rest of the world.

it mightn't help in this case, but just a reminder that there's a bunch of LS functions sitting inside ColdFusion... not everyone puts month before day (or uses Fahrenheit, pounds, miles, etc ... and don't get me started on whitworth and BSF spanners...)

Posted on February 21, 2008 at 10:40 PM

2. Gary F says:

As I'm in the UK I just checked the docs for a Euro equivilent and yes, there's "eurodate". But look what it says about this:


[QUOTE] eurodate: any date-time value, including US date formats and time values [/QUOTE]


Hang on! Isn't the whole point of "eurodate" to ensure only the European date format is accepted? But it's saying it also accepts the US date format? Duh!

Posted on February 22, 2008 at 2:32 AM

3. Travis Heeter says:

That helped a lot. Thanks.

Posted on May 25, 2011 at 11:12 AM

4. Chaln L says:

It really helped. Thanks .

One more: in Coldfusion 6, "1/1/2011a" is considered as a validate date by isdate(), and if you use dateFormat('1/1/2011a', "MM/DD/YYYY"), you will get "01/01/0201"

Posted on October 18, 2011 at 7:11 PM