Reputation: 35
How can I check the <input type="date">
to verify if it exceeds today's date or not before submitting ?
The form will not submit if future date is in the input,
<html>
<head>
</head>
<body>
<form>
<ul>
<li>
<label>Member Since </label>
<input id="since" name="since" size="2" maxlength="6" value="" type="date" required />
</li>
<li>
<input type="Submit" name="Submit" id="btnsubmit" value="Submit" onclick="checkDate();" />
</li>
</ul>
</form>
</body>
</html>
Upvotes: 0
Views: 454
Reputation: 381
You need to check two things.
1) was a valid date entered,
2) is the date in the range you want it.
try the code bellow, it will check for both conditions before allowing a submit.
<html>
<head></head>
<body>
<script>
function checkDate() {
var val = new Date(document.forms["frm"]["since"].value);
var now = new Date();
if (isNaN(val.getTime()) || (val>now)) {
alert('invalid date');
return false;
}
return true;
}
</script>
<form name="frm" onsubmit="return checkDate()">
<ul>
<li>
<label>Member Since </label>
<input id = "since" name="since" size="2" maxlength="6" value="" type="date" required/>
</li>
<li>
<input type="Submit" name="Submit" id="btnsubmit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
Upvotes: 1
Reputation: 712
Try converting the input value to a Date Object to compare today and the input value in your script.
input = document.getElementById("since"); // gets element
value = input.value; // form value (string)
date = new Date(value); // converts string to date object
now = new Date(); // current date
if (now > date) {
// in past
} else {
// in future
}
Upvotes: 2
Reputation: 977
Something like that should help you.
var dateText = document.getElementById('since').value;
var date = new Date(dateText);
var now = new Date();
if (date > now) {
console.log("Date needs to be in the past");
}
Upvotes: 0