Detecting an invalidly parsed date in Javascript

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?


2 Responses to “Detecting an invalidly parsed date in Javascript”

  1. Phil Says:

    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.

  2. Detecting an invalidly parsed date in Javascript « Fringley's Blog Says:

    […] reading Detecting an invalidly parsed date in Javascript on my old blog… Tags datetime, javascript, parsing, validation Categories […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: