Simple javascript date validation
Recently, I had to program a very specific CMS for a client.. I needed to do a lot of validation on client’s side.
I, like everyone else have a collection of functions I use and abuse every time I have similar requirements, but this time I decided it won’t be bad to review and optimize my code.
When I got to the part of validating dates, I did some google research to check on how other people is doing it. to my surprise I found a lot of extremely obscure and intricate ways to do it, some people even use calendar functions to check on leap years.
Here is how I do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function validateDate(dateToValidate) { /* The following four lines are just the way to validate that the date is in dd/mm/yyyy format, the way I'm expecting it. It's good for me, but maybe not for you.*/ aDate = dateToValidate.split('/'); if (aDate.length != 3) { alert('Invalid date'); return false; } /* Here is where the real validation is */ testDate = new Date(aDate[1]+'/'+aDate[0]+'/'+aDate[2]); if ((testDate.getDate() != Number(aDate[0])) || ((testDate.getMonth() + 1) != Number(aDate[1])) || (testDate.getFullYear() != Number(aDate[2]))) { alert('Invalid date'); return false; } return true; } |
The validation is done at line 16 (splitted in 3 for easier reading) of the previous snippet.
When you create a Date object (with a datestring, “year, month, day”, or whatever) it will probably never fail, even if the date is wrong.
E.g. myDate = newDate(2010, 1, 29), this is supposed to create a Date object for the 29th of February (remember January = 0) of 2010, but 2010 it’s not a leap year and February goes up to 28 only, so Javascript will just create what it can, a Date obejct for March 1st, 2010.
So what we are doing here is just creating a new Date object with day, month and year from the user input, and then jut verify that day, month and year of that object are equal to the ones provided. Just one line. :)