Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Greetings,

I need to validate a date field in JavaScript that acquires today's date, compares today's date to the posted date, and, if the posted date is older than today's date, default the field value to today's date. I have listed my sample code below...

JavaScript
function isValidDate(dateString)
{
    var todaysdate = (Date.now());
    // First check for the pattern
    var regex_date = /^\d{1,2}\-\d{1,2}\-\d{4}$/;

    if (!regex_date.test(dateString))
    {
        return false;
    }

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

    // Check the ranges of month and year
    if (year < 1000 || year > 3000 || month == 0 || month > 12)
    {
        return false;
    }

    var posteddate = new Date(dateString);
    if (todaysdate > posteddate) {
        return false;
    }

    var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    // Adjust for leap years
    if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
    {
        monthLength[1] = 29;
    }

    // Check the range of the day
    return day > 0 && day <= monthLength[month - 1];
}
Posted
Updated 9-Sep-14 7:04am
v3
Comments
George Jonsson 9-Sep-14 13:06pm    
So what is the problem?

1 solution

Maybe this Codeproject article might help.

JavaScript Date Validation[^]
 
Share this answer
 
Comments
Techie05 9-Sep-14 13:44pm    
George,

Thank you for a quick response...

The code that I posted shows that there is a validation process in place whereby the date entered is validated to ensure that it is not a "past" date. What I need is for the code to go a little further and set the field value to "today's" date if the data entered by the user is a "past" date or if no data was entered.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900