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!
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
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!
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 - 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 - 2 is done this way
- 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 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!