javascript - 在 jsp 中拒绝 future 日期

标签 javascript date

我的 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/

相关文章:

javascript - 使用 ".text"或 ".textContent"时保留换行符。可能的?备择方案?解决方法?

javascript - 在 gallery.php 中单击时突出显示缩略图

javascript - 如何在内部类中找到正确的 "this"对象?

javascript - 如何从 javascript Date 对象获取时区字符串?

java - 静态方法总是同时返回

date - 是否有关于如何在有进位的日期上增加月份的建议或规范?

javascript - 将 JSON 数组与 jQuery 相结合

javascript - 如何在 map 应用中实现稳定的缩放

java - Android DatePicker 和 Java 的日期

java - 使用 Date(milliseconds) 构造函数初始化日期