View Single Post
Old 11-01-2012, 10:22 PM   PM User | #2
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,530
Thanks: 0
Thanked 503 Times in 494 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
The simplest way to validate a date in mm/dd/ccyy format in JavaScript is to load it into a date object and then test to make sure that the day, month and year in the date object are the same as those in the original string.

Code:
function isValidDate(dateString)
{
    // First check for the pattern
    if(!/^\d{2}\/\d{2}\/\d{4}$/.test(dateString))
        return false;

    // Parse the date parts to integers
    var parts = dateString.split("/");
    var day = +parts[1];
    var month = +parts[0]-1;
    var year = +parts[2];

   if(year < 1000 || year > 3000) return false;

    var dt = new Date(year, month, day);
    if (dt.getDate() !== day || dt.getMonth() !== month || dt.getFullYear() !== year) return false;
    return true;
}
You could shorten the code slightly more by substituting a string.match for the regexp.test and string.split so as to both validate that the code contains the three numeric values and split them into an array in a single command.

Are you sure that you are only passing the date without any leading or trailing spaces? Since you don't trim off any spaces a single space added to the date would cause it to fail validation.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 11-01-2012 at 10:25 PM..
felgall is offline   Reply With Quote