Javascript DateValidation (compare two dates)

Hi friends,

Below is the code that dose date validation. To be specific, this javascript can be used for comparing two dates (eg., to validate for a case where Start date should be before the End date).

if (Date.parse(fromDate) > Date.parse(toDate)) {
alert("Invalid Date Range!\nStart Date cannot be after End Date!")
return false;
}

So how to test this code??
Answer: Have two textboxs in your page and ask the user to entire two dates (Start date and End date). If the start date is after the end date, this code would thrown an alert.

You can get the file from here which has code that performs a simple eg.,

Hope this helps you.
Love MJ :)

5 Responses

  1. u’r sample code will not working properly,test it once

  2. I gave 12-08-2010 in the start date and 12-08-2009 in the end date and I got a alert saying ‘Invalid date’.

    So, It working buddy ;) .

    Can you please tell me the reaon for your comment? I’ll try to answer your question.

    Freddie

  3. Hi,

    When i put your code in my javascript function Date.parse method gives me “NaN”.
    Could you tell me just other method which has javascript support ?

    CodVenture

  4. Hello CodVenture, Please give me a explanation on what exactly you are looking for so that I may try to solve your issue.

    This code accepts only numerics. Probabily you would have used ‘mar’ for march which should be 03

    If you still find this as an issue please give me your exact scenario so that i can help you to modify the code accordingly

    Freddie

  5. Try this ….
    var startDateValue = new Date(startDateVal);
    var startDateValuecmp = startDateValue.getTime();
    var endDateValue = new Date(endDateVal);
    var endDateValuecmp = endDateValue.getTime();
    if( startDateValuecmp > endDateValuecmp ){
    alert(“End Date cannot be less than Start Date”);
    }

    Regards Nitil

Leave a Reply