簡體   English   中英

HTML 輸入日期:不允許用戶使用鍵盤輸入未來日期

[英]HTML input date: Don't allow user to type future dates using keyboard

我可以很容易地阻止用戶使用箭頭或鍵盤箭頭編寫未來的日期,如下所示,我還想阻止他在輸入字段中寫入未來的日期。

我不想完全禁用鍵盤輸入,因為它很有用

 document.getElementById("date_end").addEventListener("change", event => { if (event.target.value > event.target.max) { event.target.value = event.target.max; } });
 <input type='date' name='date_end' id='date_end' max="2023-01-03" value="2020-01-01">

上面的代碼片段有效,但我最終使用了下面的代碼片段,不知道為什么,使用上面的代碼更好。

 const dateToDate = date => { let params = date.split('-'); params[1]--; // months are zero indexed return new Date(...params); }; let end_date_input = document.getElementById('date_end'); end_date_input.addEventListener('input', function(){ if(dateToDate(this.value) > dateToDate(this.max)){ this.value = this.max; } });
 <input type='date' name='date_end' id='date_end' max="2023-01-03" value="2020-01-01">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM