NOTE: As of July 12, 2009, this blog has been discontinued and replaced by the new Thought Delimited blog. All of the entries in this blog can be found there, along with new posts.
Preventing Non-Existent Dates with JavaScript
You could write a date validation script that took the month and day value submitted by the user and checked it against a list of the maximum number of days for each month, but then your code would also have to determine if the year selected by the user was a leap year in case the user entered "February 29" as their date of choice.
There's a more straightforward way to check the validity of the submitted date: create a JavaScript Date object using the year, month, and day submitted by the user, then extract the year, month, and day values from the newly created Date object and compare those integer values against the ones submitted by the user:
//Since JavaScripts counts months starting from 0 (January is 0), subtract 1 from the month integer submitted by the user
var formattedMonth= userSubmittedMonth-1;
var testDate= new Date(userSubmittedYear,formattedMonth,userSubmittedDay,0,0,0,0);
if (testDate.getFullYear() != userSubmittedYear || testDate.getMonth() != formattedMonth || testDate.getDate() != userSubmittedDay)
{
alert("The date that you entered doesn't exist (like Feb. 31)");
}
This works because JavaScript's date creation function will accept the integer values for a non-existent date like April 31, 2009 (4, 31, and 2009), but it will quietly translate it into it's real-life equivalent, in this case May 1, 2009. So the integer values pulled from the date object via the getFullYear(), getMonth(), and getDate() functions will not match the integers originally passed into the date creation function, and you know there's a problem.


There are no comments for this entry.
[Add Comment]