Wednesday, September 20, 2006

IsDate and Agent Zed

While reviewing code I found an interesting bug in a VB component today.
There is a piece of software that should validate if a given input value
represents a correct date.

Unfortunately it just used the IsDate() function to check the value.
If I reduce the code to its minimum it does something similar to:

Private Sub Command1_Click()
   Dim inputValue As String
   inputValue = "28.02.06"
   MsgBox IsDate(inputValue)
   MsgBox CDate(inputValue)
End Sub


This works as expected: the inputValue represents a date (so we get "True")
and after the date conversion we get the correct date: 28.02.2006.

But have you tried with "31.02.06" - an input value which is not a
correct date (at least if you think of the format dd.mm.yy)

It is silently accepted by the code and VB is converting it into
the "06.02.1931"! Beside the fact that this is the day where actor
Rip Torn was born (who played Agent Zed in Men in Black) we found the
reason for accepting the bad input value.

So if VB cant find a matching date in the right order it just parses
the string reverse and checks for a reasonable date value.

Let's do a quick check in .NET using C#:

DateTime date = DateTime.Parse("31.02.06");

Fortunately this is not an issue since a FormatException is thrown.

Conclusion: never stop testing your code and when it comes to
dates remember the birth of Agent Zed...

No comments: