检查日期是否过去没有提交表单 [英] Check if date is in the past without submitting form

查看:97
本文介绍了检查日期是否过去没有提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,我想检查一个日期是否在过去。我想在表单提交之后立即检查日期。

I have this code that I want to check if a date is in the past. I want to check it as soon as the date is entered, before form submission.

<input id="datepicker" onchange="checkDate()" required class="datepicker-input" type="text" data-date-format="yyyy-mm-dd" >

<script type="text/javascript">
 function checkDate() {
   var selectedDate = document.getElementById('datepicker').value;
   var now = new Date();
   if (selectedDate < now) {
    alert("Date must be in the future");
   }
 }
</script>

如果我在过去输入日期(例如2014-12-03),则无效它不显示警报。

This does not work, if I enter a date in the past (e.g. 2014-12-03) it does not display the alert.

推荐答案

所有您需要做的是将由 < input> 转换为使用Date构造函数的日期新日期(2014-06-12)

All you need to do is convert the string produced by the <input> into a Date using the Date constructor new Date("2014-06-12")

 function checkDate() {
   var selectedText = document.getElementById('datepicker').value;
   var selectedDate = new Date(selectedText);
   var now = new Date();
   if (selectedDate < now) {
    alert("Date must be in the future");
   }
 }

<input id="datepicker" onchange="checkDate()" required class="datepicker-input" type="date" data-date-format="yyyy-mm-dd" >

这篇关于检查日期是否过去没有提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆