我目前正试图在一个网站上创建一个表单,其中一个人在提交表单之前填写一个日期。如果用户在今天之前输入日期,它将不会提交表单并发出一个声明为"Date cannot be before today"
的警告。
然而,我遇到了一个问题,我的JavaScript算法是错误的,我无法找出是什么导致了这个问题。问题是:日期不重要,用户可以从表单中从2020-01-01
输入maxlength
下面的任何日期(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>
发布于 2018-07-21 00:13:18
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() {
...
发布于 2018-07-21 00:01:52
更新代码以执行日期检查。
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());
}
发布于 2018-07-21 00:18:25
您可以使用moment.js库:https://momentjs.com/
if(moment(doa)).isBefore())
return false;
return true;
如果没有任何东西传递给moment#isBefore,它将默认为当前时间。
https://stackoverflow.com/questions/51453962
复制