我有一个表单,如果用户选择了上一个显示错误的日期,则会接受用户的日期。
问题
当用户选择当前日期时,它会给出错误并且休息一切正常。
function tablebookval() {
var seldatetab = document.getElementById("selectdateTab").value;
var todaytab = new Date();
//compare date
if (Date.parse(seldatetab) < Date.parse(todaytab)) {
alert("Enter a valid date ");
return false;
} else {
alert("Your booking is registered we will call you within an hours");
return true;
}
}
<input type="date" id="selectdateTab" onblur="tablebookval()" />
答案 0 :(得分:0)
如果您添加console.log(Date.parse(seldatetab),Date.parse(todaytab))
,您会看到NaN(非数字)小于任何数字
如果类型是日期,则必须输入小于今天的日期才能看到验证失败。然后你的代码工作
如果你想让TODAY工作,你需要规范化日期
function tablebookval() {
var seldatetab = document.getElementById("selectdateTab").value,
today = new Date(),
selDate = new Date(Date.parse(seldatetab));
today.setHours(12,0,0,0); // normalise
selDate.setHours(12,0,0,0);
//compare date
console.log(selDate, today, selDate.getTime() < today.getTime())
if (isNaN(selDate) || selDate.getTime() < today.getTime()) {
alert("Enter a valid date ");
return false;
} else {
alert("Your booking is registered we will call you within an hours");
return true;
}
}
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
return tablebookval(); // validate
}
}
&#13;
<form id="myForm">
Date:
<input type="date" id="selectdateTab" />
<input type="submit" value="Book" />
</form>
&#13;