3 回答

TA貢獻1831條經(jīng)驗 獲得超4個贊
請嘗試一下
注意:嘗試使用日期選擇器進行日期選擇
function validateDOB(){
if(document.getElementById('dob').value==''){
alert('Please select a date')
return false
}
var dob=document.getElementById('dob').value
console.log(dob)
var today = new Date();
var birthDate = new Date(dob);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
if(age<16){
alert('You are not eligible. Age should be above 16...!!!')
}
}
<input type='date' id='dob'>
<button onclick='validateDOB()'>validate</button>

TA貢獻1884條經(jīng)驗 獲得超4個贊
由于您的代碼已經(jīng)檢查了用戶是否選擇了出生的年,月和日,因此您可以在檢查通過后調(diào)用我的函數(shù)。
function isValidDate(year, month, date) {
var dob = new Date(year, month-1, date);
if (dob.getDate() != date)
alert("Invalid date value");
else if ((dob.getMonth() - month) != -1)
alert("Invalid month value");
else if (dob.getFullYear() != year)
alert("Invalid year value");
}
添加回答
舉報