Javascript - 表单提交,必填字段留空

Javascript - Form submits with required field left empty

编辑: 我的问题措辞有误。如果我将必填的 DOB 字段留空,它会显示 'Welcome' 只有当用户 DOB 表明他们已超过 17 岁时,我才希望它说。在它说欢迎之后,它会告诉我填写必填的 DOB 字段。为什么没有输入DOB还是说welcome?

以下是我认为相关的所有代码:

出生日期字段 出生日期:

<input type="text" name="Date" id="dateof" placeholder="YYYY-MM-DD" title="Enter your date of birth in the form YYYY-MM-DD" required /><br/><br/>

出生日期验证函数

var minAge = 17;
var today = new Date()

function calcAge(birthDate, todaysDate) {
    todaysDate = new Date(today);
    var givenDOB = document.getElementById('dateof').value; /*date of birth entered*/
    var birthDate = new Date(givenDOB);
    var years = (todaysDate.getFullYear() - birthDate.getFullYear());

    if (todaysDate.getMonth() < birthDate.getMonth() ||
        todaysDate.getMonth() == birthDate.getMonth() && todaysDate.getDate() < birthDate.getDate()) {

        years--;
    }

    return years;
}


function setAge() { 

    var age = calcAge();
    if (age < minAge) {
        alert("Sorry, the minimum age is 17!");
    } else

        alert("Welcome!");

}

您可以使用 javascript 检测空日期字段并发送警报。

修改 javascript 应该可以。尝试这样的事情:

function calcAge(birthDate) {
  todaysDate = new Date(today);
  /*date of birth entered*/
  var birthDate = new Date(givenDOB);
  var years = (todaysDate.getFullYear() - birthDate.getFullYear());

  if (todaysDate.getMonth() < birthDate.getMonth() ||
    todaysDate.getMonth() == birthDate.getMonth() && todaysDate.getDate() < birthDate.getDate()) {
    years--;
  }

  return years;
}


function setAge() { 
  var givenDOB = document.getElementById('dateof').value;
  if (givenDOB == "") {
    alert("Sorry, you must enter your date of birth!");
  } else {
    var age = calcAge(givenDOB);
    if (age < minAge) {
      alert("Sorry, the minimum age is 17!");
    } else
      alert("Welcome!");
    }
  }
}