[英]JavaScript date validation for HTML
我目前正在嘗試在網站上創建表單,在此網站上,人們需要填寫日期才能提交表單。 如果用戶輸入今天之前的日期,它將不會提交該表單並給出警告,指出"Date cannot be before today"
。
但是,我遇到了一個問題,即我的JavaScript算法錯誤,並且我無法找出導致問題的原因。 問題是:日期無關緊要,用戶可以從表單的maxlength
輸入2020-01-01
以下的任何日期(JavaScript不起作用)
function checkForm() {
var answ = validateDate(document.getElementById("doa").value);
if (answ == false) {
return false;
}
return true;
}
function validateDate(doa) {
var d = new Date(doa);
var n = new Date();
if (d <= n) {
alert("Date cannot be before today");
return false;
}
return true;
}
我的表格:
<form action="advertResult.html" onsubmit="return checkForm()">
<label class="formText">First Name:</label>
<input type="text" id="firstName" name="firstname" placeholder="" required>
<label class="formText">Last Name:</label>
<input type="text" id="lastName" name="lastname" placeholder="" required>
<label for="commission" class="formText">Type of Commission</label>
<select id="commission" name="commission" required>
<option value="drawing">Art</option>
<option value="video">Video</option>
</select>
<label for="doa" class="formText">Select a date for discussion</label>
<input type="date" name="date" id="doa" max="2020-01-01" required>
<input type="submit" value="Submit">
</form>
更新您的代碼以進行日期檢查
function checkForm() {
return validateDate(document.getElementById("doa").value);
}
function validateDate(doa) {
var d = new Date(doa);
var n = new Date();
return (d.getFullYear() >= n.getFullYear()) &&
(d.getMonth() >= n.getMonth()) &&
(d.getDate() >= n.getDate());
}
HTML代碼引用全局函數checkForm
,而JS代碼可以通過多種方式定義
除非它是由老式的<script>
標記(直接在HTML中或使用src
屬性)包含的,否則JS的包含方式(例如使用webpack)可能會將函數轉換為本地函數,並且沒有定義全局checkForm
在這種情況下,您可以定義一個全局函數( http://jsfiddle.net/w1m6c7v0/7/ ):
window.checkForm = function() {
...
甚至更好的是,在JS中添加事件偵聽器( http://jsfiddle.net/w1m6c7v0/6/ ,但如果您使用多種形式,請使用id
屬性):
document.querySelector('form').onsubmit = checkForm
function checkForm() {
...
您可以使用moment.js庫: https ://momentjs.com/
if(moment(doa)).isBefore())
return false;
return true;
如果未將任何內容傳遞給moment#isBefore,它將默認為當前時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.