[英]How to validate age in javascript with input date type
So I made an input type="date"
but was unable to validate if the user entered a valid (18+ yrs old).所以我输入了
type="date"
但无法验证用户是否输入了有效的(18 岁以上)。 How can I make it validate?我怎样才能使它验证?
Sample code:示例代码:
HTML: HTML:
<label>
Birthdate:
<br /><input
type="date"
id="birthdate"
placeholder="Enter birthdate"
/><br />
<span class="notif" id="bday"></span>
</label>
JS: JS:
var birth = document.getElementById('birthdate').value;
if (birth == '') {
document.getElementById('bday').innerHTML = 'Please enter birthdate.';
}
I can only validate if there is no user input.我只能验证是否没有用户输入。 I want it to store an error in
notif
if the age is under 18 years old.如果年龄低于 18 岁,我希望它在
notif
中存储错误。
You can use the min/max attribute of the date input that is natively provided by HTML5.您可以使用 HTML5 原生提供的日期输入的 min/max 属性。 Check out this link for more information on the same - https://www.w3schools.com/tags/att_input_min.asp
查看此链接以获取更多信息 - https://www.w3schools.com/tags/att_input_min.asp
you can check differnce between their birthday date and today's date:您可以检查他们的生日日期和今天日期之间的差异:
var their_date = new Date(2010, 6, 17);
var today = new Date();
var date2 = new Date(today.getFullYear(),today.getMonth()+1,today.getDate());
var diff = new Date(date2.getTime() - their_date.getTime());
console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.