输入字段中仅允许日期为 18 年以上

问题描述 投票:0回答:3

我想要一个仅允许 18 岁以上人士输入日期的输入字段:

<input id="txtDOB" type="text" name="txtDOB">
javascript html validation view user-input
3个回答
0
投票

你必须写一些JS

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear()+18;
 if(dd<10){
        dd='0'+dd
    } 
    if(mm<10){
        mm='0'+mm
    } 

today = yyyy+'-'+mm+'-'+dd;
document.getElementById("txtDOB").setAttribute("max", today);

0
投票

Wimanicesir 的答案很好,但我会做一个更改,我们需要减去 18 才能得到 18 岁以上的最大年龄,而不是添加 18。

const today = new Date()
let dd = today.getDate()
let mm = today.getMonth()+1 // January starts at 0, so we add 1 to get  the correct number for the month.
let yyyy = today.getFullYear() - 18; 
 
if(dd<10)dd = "0"+dd
if(mm<10) mm = "0"+mm

today = `${yyyy}-${mm}-${dd}`

document.getElementById("txtDOB").setAttribute("max", today);

0
投票

Patrick 的答案有语法错误。

today
变量无法重新分配,因为它是 const。

这是基于帕特里克解决方案的更简短且正确的答案。

const eighteenYearsAgo = () => {
    const today = new Date()
    let dd = String(today.getDate()).padStart(2, 0)
    let mm = String(today.getMonth() + 1).padStart(2, 0)
    let yyyy = today.getFullYear() - 18;

    return `${yyyy}-${mm}-${dd}`
})
© www.soinside.com 2019 - 2024. All rights reserved.