Sunday, August 29, 2010

How to accept only strict dates using javascript validations

Well, well, well yes there are a thousand (or even more) date pickers around to help users to choose a date.

But recently in a project, I was faced with a situation where requirement was, to allow user to choose a date via a date picker but also allow them to type in the date if they wish to do so!

Hummm.... I know its a standard requirement. We where using JQuery as our javascript framework and JQuery-UI for the date picker.

Showing the date picker is a child's play all we have to do is:

  • Include the jquery library
  • Include the jquery-ui library and css
  • Invoke the datepicker method on the chosen input field
But allowing user to type in the date is a bigger challenge.
Why? Because they can type in any random value which may not be a valid date.

There are lots of plug-ins available in jquery to stop users from entering chars in date fields etc. Thats easy you see! But the problem is making sure user enters a valid date.

Lets assume that the date format we are using is mm/dd/yyyy.
If the user enters 13/01/2010, clearly its an invalid date since we have only 12 months so far!

But the javascript Date class is very very lenient and it converts the date 13/01/2010 to 01/01/2011 which is a valid date.

And hence for javascript 13/01/2010 is a valid date. But for us, humans its an invalid date!

So how do we validate such invalid inputs and show errors to users?

How do they do it!

The approach I take is as follows. I use two level of defense strategy and heres what I do
  • Step - 1: Use the javascript Date class to find whether user has entered a valid date? If date parsing fails then show and error to the user. This is our first level of defense
  • Step - 2: If we are able to parse the date, then we need to verify if its a valid date. If its not we show an error to the user. This is our second level of defense.
Step - 1 is easy and I am not going to show it.

Step - 2 is done this way

Basically, we first let javascript parse the date entered by user and then we split the date into parts and then verify that
  • The month entered by user is the same as the month held by the parsed date
  • The day entered by user is the same as day held by the parsed date
  • The year entered by the user is the same as the year held by the parsed date
If any of the above conditions fails, we return and error to the user.
If all of the above conditions are true, then user has entered a valid date

The Sample Code:

If you try the above code we get two alerts the first one is Invalid Date. and the second one is Date is valid. and that is exactly what we want!

Mission accomplished!
Have some Fun!