1

I'm trying to add validation the type = "month" field on my form so that if the date entered is not greater then-current date it will give an alert.

So far iv managed to link function to my submit button using onlcick, iv got a variable that gets the current date and stores it in another variable, and iv attempted to write if/else statements but I believe the logic is incorrect.

I'll only show the code that applies to my question, if more code is required I can provide.

My form:

    <div id="container">
    <form method="post" action="www.someplace.php" id="MovieForm">
         <div id="col-50">
            <label for="expmonth">Expiry Date</label>
            <input type="month" id="expmonth" name="expmonth">
                   </div>
<div id="col-50">
        <button type="submit"  onclick="return ValidateForm();"  id="btn"><Strong>Proceed to checkout</Strong> </button>
          </div>
      </form>

My JS Function:

<script>
function ValidateForm() {
  var expValidate = document.getElementById("expmonth").value;
  var today = new Date();
  var date = today.getFullYear()+'-'+(today.getMonth()+1)
  var isValid = false;

    if (expValidate > today) {
        isValid = true;
        alert("correct month") 
    }
    else {
        alert("Wrong month")
        return false;
    }
}

So if I was to run that code and enter a date above the current one it would give me an alert saying "The wrong month" then return me to the form (even though it should be saying "Correct Month" then sending me to the next page).

But the same thing also happens if I was to run the code and enter a month below the current date, it still gives the message "The wrong month" then return me to the form.

Yaser Darzi
  • 1,480
  • 12
  • 24
Huseyin Yesiler
  • 85
  • 1
  • 2
  • 11

1 Answers1

0

Try this. It should work to match date using date input type.

<input type="date" id="expmonth" name="expmonth">

function ValidateForm() {
    var date = new Date($('#expmonth').val());
    console.log(date);
    var today = new Date();
    console.log(today);

    if (date >= today) {
        isValid = true;
        alert("correct month") 
    } else {
        alert("Wrong month")
        return false;
    }
}
Vaibhavi S.
  • 1,083
  • 7
  • 20
  • Thanks for the comment, that does indeed fix the problem but this is for homework so they want us to learn how to use type month with JS. Thank you for taking the time to answer my question though. – Huseyin Yesiler Oct 01 '19 at 12:08