[英]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.