kl00t
kl00t

Reputation: 45

Can you explain why this javascript is incorrect?

I am expecting this script to return an alert if the Expiry Date is in the past, otherwise to show OK.
I was not expecting the script to fall into the Else "Error" statement.

Can anyone explain what is going on?

<!DOCTYPE HTML>
<html>
<body>

<div id="test"></div>

  <script>
    var expirymonth = "3";
    var expiryyear = "2017";

    if (expirymonth != null != null && expiryyear != null)
    {
        var currentDate = Date();
        var expiryDate = new Date(parseInt(expiryyear),parseInt(expirymonth - 1),1);
        if (expiryDate < currentDate)
        {
            window.alert("Expiry Date must not be in the past.");
        }
        else if (expiryDate > currentDate)
        {
            window.alert("OK");
        }
        else
        {
            window.alert("Error");
        }
    }
  </script>

</body>
</html>

Upvotes: 1

Views: 83

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

Date() returns a string. You can't compare it to a date.

Replace

var currentDate = Date();

with

var currentDate = new Date();

(fix also the obvious typo that was pointed in comment by Davin Tryon)

Upvotes: 7

Related Questions