0

So I have a checkDate() function that I use to verify the date entered on a web form is not in the past before submitting. The problem is, this function also returns an error if the date entered is today's date. I'm assuming this has something to do with how datetimes are formatted as DD:MM:YYYY HH:MM:SS.sss and then converted to their epoch value, but I'm not sure how to go about validating that the entered date is NOT today while still checking that it's not a past date.

I've posted my checkDate() function in its entirety below:

Please note: the textbox with the date string we are checking against is named txtNeededBy.

function checkDate() {

    var date = new Date($("#txtNeededBy").val());
    ValidateDate = false;

    if (Date.parse(date) < Date.now()) {
        sb.append("<li>Needed by date must not be in the past.</li>");
        $("#txtNeededBy").addClass("input_error");
        ValidateDate = true;
        if (sb.toString().length > 0) {
            $(".Errors").html(sb.toString());
            $(".Errors").show();
            return false;
        }
    } else {
        $("#txtNeededBy").removeClass("input_error");
    }

    if (ValidateDate === true) {
        return false;
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Michael H
  • 185
  • 1
  • 2
  • 9
  • Duplicate of http://stackoverflow.com/questions/2698725/comparing-date-part-only-without-comparing-time-in-javascript – ChrisV Feb 03 '15 at 01:52
  • On a side note: you do not need the `=== true` at the end of your code. An if statement only runs when the condition is true. If you have a boolean variable (true/false), you won't have to check if it's value `=== true`, because what you are doing is actually `if(true === true)`. `true === true` returns true, which means you could have left out the check in the first place. Also, why are you declaring your `ValidateDate` without the `var` keyword? – Ruben Rutten Feb 03 '15 at 01:53
  • I think I'm going to try the answer posted by ChrisV. As for the ValidateDate variable, this is a global variable declared elsewhere, my bad for not including that. – Michael H Feb 04 '15 at 20:07

1 Answers1

0

I would strongly recommend using a library like Date.js

That library has an .is() method that allows you to do these sorts of comparisons extremely easily. Don't reinvent the wheel :)

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236