验证日期,确保该日期不能是将来或过去的日期

问题描述 投票:0回答:4

我有这个带有日期输入的表格。 Javascript 中确保所选值既不是未来日期也不是过去日期的最佳方法是什么。我已经实现了 jQuery 日期选择器来选择日期,请参阅下面的代码

<html>
  <!--maina-->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="main.css" rel="stylesheet" type="text/css"/>

<script>
$(function() {
    var date = $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
});

function ValidateForm(){
	var date_of_circulation = document.forms["myForm"]["date_of_circulation"].value;
		if (date_of_circulation == null || date_of_circulation ==""){
			alert ("You have to select the date the manuscript was circulated");
			return false;
		}
	}
</script>

<form enctype="multipart/form-data" name = "myForm" action = "" onsubmit="return ValidateForm()" method = "post">
Date of circulation:<input name="date_of_circulation" input type="text" id="datepicker"></p>
<input name = "add_manuscript" type="submit" value = "submit">
</form>
</html>

javascript jquery validation
4个回答
3
投票

你可以这样做

var yourDate = new Date("12/5/2015"); //input value

var todayDate = new Date(); //Gets the today's date value

你必须使用函数

setHours

if(yourDate.setHours(0,0,0,0) == todayDate.setHours(0,0,0,0));
{
    //Do your stuff
}

注意:您也可以使用 jquery 的日期选择器来完成

var currentDate = new Date();
$("#datepicker").datepicker("setDate", currentDate);

这样您就可以确定今天的日期已被选择。

编辑:您还可以查看datejs

datejs API 文档


0
投票

我通过引入 maxdate 和 Mindate 找到了一个有效且简单的解决方案,如下所述:日期选择器限制日期范围。在重新考虑验证规则后,我决定 date_of_circulation 值的逻辑验证可以是过去的日期,但不能超过当前日期,因此将日期选择器中的 var date 更改为

var date = $("#datepicker").datepicker({ maxDate: new Date,dateFormat: 'yy-mm-dd', minDate: new Date (0) });


0
投票
userInput.max = new Date().toISOString().split("T")[0];

-1
投票

如果日期字段必须设置为当前日期,则没有未来或过去的日期 将文本字段的默认值设置为当前日期,您不需要使用日期选择器,因为没有任何其他日期选项的日期选择器对用户来说不友好。 另外,通过这种方式,您不需要在提交时验证表单。

<input name="date_of_circulation" input type="text" id="datepicker" value="<?php echo date('Y-m-d'); ?>" readonly="readonly">

将输入框设置为只读,以便用户无法更改日期。

© www.soinside.com 2019 - 2024. All rights reserved.