Javascript - 表单提交必填字段为空

时间:2015-01-27 23:12:48

标签: javascript forms

编辑:我说错了我的问题。如果我将所需的DOB字段留空,则会显示'Welcome',我希望它仅在用户DOB建议他们超过17时才说出来。在欢迎之后,它会告诉我填写所需的DOB字段。当没有输入DOB时,为什么还说欢迎?

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

出生日期 DOB:

<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!");

}

1 个答案:

答案 0 :(得分:1)

您可以使用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!");
    }
  }
}