编辑:我的问题措辞错误。如果我将必填的出生日期字段留空,它会显示'欢迎'
,只有当用户出生日期表明他们已年满 17 岁时,它才会显示。在显示欢迎字段后,它会告诉我填写所需的 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!");
}
最佳答案
您可以使用 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!");
}
}
}
关于Javascript - 表单提交时必填字段留空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28181795/