I’m a beginner to HTML, Javascript, and coding in general. For an assessment, I’m required to create a form with HTML, and validate it with a Javascript file. If an inputted answer isn’t valid, it should return false. For a credit card, a user is required to input an expiry date, and if the date has already passed, it should return false. Though despite this, no matter how much I troubleshoot, it always returns true with no errors. Any help would be appreciated!
HTML
<form name="userForm" onsubmit="return validateForm()">
<fieldset>
<legend>Payment details</legend>
<div>
<lable for="exMonth">Expiry MM/YY</lable>
<select id="exMonth" name="exMonth">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<select id="exYear" name="exYear">
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option>
<option value="2027">2027</option>
<option value="2028">2028</option>
</select>
</div>
</fieldset>
<br>
<input type="submit">
<button>Help</button>
<p id="demo"></p>
<script src="../js/assessment1.js">
</script>
Javascript
function validateForm()
{
var exMonth=document.getElementById("exMonth");
var exYear=document.getElementById("exYear");
var date = new Date ();
var month = date.getMonth();
var year = date.getFullYear();
if (year> exYear || (year === exYear && month >= exMonth))
{
alert("Your expirey date has passed");
return false;
}
alert("Thanks");
return true;
}
I’ve honestly been troubleshooting so much I’ve lost what I’ve already tried. I’ll take any advice that can be provided 🙂
2
Answers
Here is the reasons of your issue:
here is a correct js code:
I’ve seen you made mistakes in getting value of Exmonth and Exyear. and another error is that you have to add 1 to currentMonth because value of January is 0.
I hope this code will help your problem. if you have any problem, feel free to reach out me.