【问题标题】:Javascript - Form submits with required field left emptyJavascript - 表单提交,必填字段留空
【发布时间】:2015-01-28 07:26:46
【问题描述】:

编辑:我的问题措辞错误。如果我将所需的 DOB 字段留空,它会显示'Welcome',我希望它仅在用户 DOB 建议他们超过 17 岁时才说。在它说欢迎之后,它会告诉我填写所需的 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!");

}

【问题讨论】:

  • 您的浏览器可能或尝试输入required=required
  • 你能分享你所有的表单代码吗?

标签: javascript forms


【解决方案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!");
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2011-10-31
    • 2014-03-07
    • 2018-06-28
    • 2013-06-29
    相关资源
    最近更新 更多