When parsing a date in Javascript, it is important to ensure that the resultant object has been parsed correctly. This is made slightly tricky as the resultant object will always be a Date object if created with
new Date().
The problem is compounded by differences between IE and other browsers. IE will return a NaN whereas other browsers will report "Invalid Date".
Use the following code to be sure:
var d = new Date("Malformed date")
if (d != "NaN" && d != "Invalid Date") {
// date is good
} else {
// date is bad
}
Does anyone else have any good ways of doing this detection?
November 25, 2009 at 12:19 am
Useful tip, I didn’t realise that IE returned a different error.
Generally when I’m working with JavaScript or php I will run a bit of serverside validation to check the date. The method depends on what system I use but there are plenty of options. I’ve also used scripts like Validator and Valid8 which can assist with this and provide useful feedback to the user.
I’m curreny developing an app where it I’d vital that the user enters the date correctly so I’ve split the input box into three (date, year, month). In most cases this is autofilled so it’s obvious what is expected but I’ve also provided a jQuery ‘date picker’ tool to help. One the forms lose focus I run a quick client-side validation tool that pads and alters the date as necessary. Finally, when the form is submitted, I run a few more checks on the server side, just in-case the user has disabled JavaScript or the script has not fully loaded.
All that is quite a lot of effort but like I said, the dates are vital in this case.
August 28, 2010 at 1:34 pm
[...] reading Detecting an invalidly parsed date in Javascript on my old blog… Tags datetime, javascript, parsing, validation Categories [...]