我有以下Javascript代码。这可以防止日期为空,但我也需要它来阻止客户在今天之前的任何一天选择;我该怎么做?
HTML
<form name="myForm" method="post" action="http://www.randyconnolly.com/tests/process.php" onsubmit="return submitFunction()">
<table border="1" >
<tr>
<td>Date:</td>
<td><input type="date" name="date" id="date"></td>
</tr>
<tr>
<td><input type="Submit" value="Submit"></td><td>Click Submit to validate this form!</td>
</tr>
</table>
的Javascript
function submitFunction(myForm)
{
var errormessage =""; // Generates Error Message if true
/*Manages a control that allows the errormessage variable to determine*
whether or not it has been deemed true. If true, an error message will appaear
If false, the code will continue to move along and validate the data. */
if (document.getElementById('date').value=="")
{
errormessage+="Select a valid date \n";
document.getElementById('date').style.borderColor="red";
}
else {
document.getElementById('date').style.borderColor="green";
}
if(errormessage!="")
{
alert(errormessage);
return false;
}
}
答案 0 :(得分:0)
我创建了一个JSFiddle来实现您的验证要求
HTML
<input type="date">
<button>Check</button>
的JavaScript
var dateElem = document.querySelector('input'),
todayDate = new Date();
todayDate.setHours(0);
todayDate.setMinutes(0);
document.querySelector('button').onclick = function () {
if(dateElem.value === '') {
alert('Please choose a date!');
} else {
if(todayDate.getTime() > (new Date(dateElem.value)).getTime()) {
alert('You can not choose a date prior to today!');
} else {
alert('Valid date :)');
}
}
}