Your condition is incorrect, because, if today's date was January 15th, 2021, and you entered January 1st, 2000, it would reject it, because the day is smaller, even though the year is greater by more than 16.
The easiest way (with the less caveats) it to convert it to a Unix timestamp (a number representing the milliseconds passed since January 1th, 1970), and compare that way:
function hasDateCheck() {
const [YYYY, MM, DD] = document.querySelector("#dateOfBirth").value.split("-");
const birthDate = new Date(+YYYY, +MM - 1, +DD)
// year day hour min sec millisec
if(Date.now() - birthDate < 16 * 365 * 24 * 60 * 60 * 1000) {
console.log("below 16");
} else {
console.log("above 16");
}
}
document.querySelector("#submit").addEventListener("click", (e) => {
e.preventDefault();
hasDateCheck();
});
<input name="dateOfBirth" id="dateOfBirth" type="date" required/>
<input type="submit" id="submit" value="Submit" id="formSubmit">
You might run into issues because of leap years (for each leap year, +/- 1 day inaccuracy). You may ignore this problem (few days usually don't cause problems), implement a more complex checking behavior, or reduce the inaccuracy by adding 4 days to the date (there are approximately 16 / 4 = 4
leap years in a 16-year range):
function hasDateCheck() {
const [YYYY, MM, DD] = document.querySelector("#dateOfBirth").value.split("-");
const birthDate = new Date(+YYYY, +MM - 1, +DD)
// year day hour min sec millisec
if(Date.now() - birthDate < (16 * 365 + 4) * 24 * 60 * 60 * 1000) {
console.log("below 16");
} else {
console.log("above 16");
}
}
document.querySelector("#submit").addEventListener("click", (e) => {
e.preventDefault();
hasDateCheck();
});
<input name="dateOfBirth" id="dateOfBirth" type="date" required/>
<input type="submit" id="submit" value="Submit" id="formSubmit">