Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Friends,

I want to apply validation to start date and end date. I tried following code,
JavaScript
$("#EndDate").change(function () {
    var startDate = document.getElementById("StartDate").value;
    var endDate = document.getElementById("EndDate").value;

    if ((Date.parse(startDate) <= Date.parse(endDate))) {
        alert("End date should be greater than Start date");
        document.getElementById("EndDate").value = "";
    }
});

sometimes it shows correct message but sometimes it shows wrong message
e.g. startdate : 12/02/2014 and Enddate : 13/03/2014 it shows wrong message
I have also used Date.js file for Date.parse()

Please provide me a solution.
Thanks.
Posted
v3

Problems

  • Condition is wrong.
    Instead of...
    JavaScript
    Date.parse(startDate) <= Date.parse(endDate)

    you should do...
    JavaScript
    Date.parse(endDate) <= Date.parse(startDate)

  • Date.parse() always parses to MM/DD/YYYY, but you are trying to compare DD/MM/YYYY.
    So, after parsing, 12/02/2014 becomes 2 December 2014 and 13/03/2014 becomes 3 January 2015.
    So, it shows the alert as startDate <= endDate.

Solution
 
Share this answer
 
Comments
Hemraj Borkhade 28-Jan-14 2:02am    
Thank you,
First i parse date in DD/MM/YYYY and then compare it's now working
Glad to hear that. :) Good work. :)
Keep coding. :)

Thanks,
Tadit
C#
$("#EndDate").change(function () {
    var startDate = document.getElementById("StartDate").value;
    var endDate = document.getElementById("EndDate").value;

    if ((Date.parse(startDate) >= Date.parse(endDate))) {
        alert("End date should be greater than Start date");
        document.getElementById("EndDate").value = "";
    }
});



you are checking like start date <= end date this condition is true in your example like start date 12/02/2014 and end date 13/03/2014, so its showing wrong message.

if you need to check that, start date is not greater than end date, then you need to check like this.. start date>= end date
 
Share this answer
 
Comments
Hemraj Borkhade 28-Jan-14 0:30am    
I have tried that condition also but still the same message
Tejas Vaishnav 28-Jan-14 1:07am    
have you checked out what you have got in start-date and end-date variables?
chethan1003 4-Dec-17 8:04am    
if i use datepicker its showing datepicker is not a function

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