1

I want to compare two date fields.. I have gotten pretty close and it even works fine..

But problem comes when "ToDate" field is a

leap year>= "FromDate"

For eg:

from date= 29/02/1996
to date= 29/02/1996
to date= 29/02/1992
to date= 29/02/1995

the code works fine..

But if

from date= 29/03/1996
to date= 29/02/1996

the code fails...

this is my code

function isDate(value)
{
    var fromDate = document.getElementById("fromDate").value
    var toDate= document.getElementById("toDate").value
    var dateRegEx = null;
    dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);

    if (dateRegEx.test(fromDate)){
    }
    else{
        alert("Invalid from date");
        return false;
    }
    dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
    if(dateRegEx.test(toDate)) {
    }
    else{
        alert("Invalid to date");
        return false;
    }
    var stDate = new Date(fromDate);
    var enDate = new Date(toDate);
    var compDate = enDate - stDate;

    if(compDate > 0)
        return true;
    else
    {
        alert("Please Enter the correct date ");
        return false;
    }
    /**/
}

how to make it work for all leap years...where would i have to make changes in the code.

Codesleuth
  • 10,321
  • 8
  • 51
  • 71
razor
  • 173
  • 2
  • 14

2 Answers2

3

This is an excelent jQuery plugin to do what you want: http://momentjs.com/

red_alert
  • 1,738
  • 14
  • 24
1

Here's a solution using moment.js:

function isDate(value)
{
    var fromDate = moment(document.getElementById("fromDate").value);
    var toDate = moment(document.getElementById("toDate").value);

    if (fromDate.isValid()) {
    }
    else {
        alert("Invalid from date");
        return false;
    }

    if(toDate.isValid()) {
    }
    else {
        alert("Invalid to date");
        return false;
    }

    if(toDate.isAfter(fromDate))
        return true;
    else
    {
        alert("Please Enter the correct date ");
        return false;
    }
}

Depending on how your dates are represented, you may have to provide the moment constructor with another parameter to indicate the format. See Validation.

Codesleuth
  • 10,321
  • 8
  • 51
  • 71