我的 html 表单中有一个出生日期字段,如下所示:
Date of Birth
<input type="date" name="dob" id="dob" onchange="ageCalculation()">
在年龄计算函数中,我想拒绝 future 的日期,并且年龄不应大于 8 岁。JavaScript 是:
function ageCalculation(){
var currentDate = new Date();
var birthDate = new Date(document.getElementById("dob").value);
var difference = currentDate - birthDate;
var differenceInYears = Math.floor(difference / (1000 * 60 * 60 * 24 * 365.25));
if(birthDate.after(currentDate)|| differenceInYears>8)
{
window.alert("Age should be less than 8 years");
}
else{
document.getElementById("age").value = differenceInYears ;}
}
但是我遇到了 Uncaught TypeError:birthDate.after is not a function
在我的 htnl 表单的开头,我写了
<%@ page import="java.util.Date"%>
最佳答案
不要使用 after 来与“<”进行比较。此外,我还修改了您的 if 子句。
function ageCalculation(){
var currentDate = new Date();
var val = document.getElementById("dob").value;
var birthDate = new Date(val);
var difference = currentDate - birthDate;
var differenceInYears = Math.floor(difference / (1000 * 60 * 60 * 24 * 365.25));
if(birthDate > currentDate) {
window.alert("You cannot be born in the future");
} else if( differenceInYears>8) {
window.alert("Age should be less than 8 years");
} else {
document.getElementById("age").value = differenceInYears ;
}
}
<input type="date" name="dob" id="dob" onchange="ageCalculation()">
<input id="age"></input>
关于javascript - 在 jsp 中拒绝 future 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39199733/