[英]Javascript to validate date entered
I am new to Javascript
programming and I am trying to validate a date entered into an <input>
from a calender snippet which is obtained from an external Javascript
file. 我是
Javascript
语言编程的新手,我正在尝试验证从外部Javascript
文件获得的日历片段中输入到<input>
的日期。 I am trying to validate the date to check if the user entered a past date. 我正在尝试验证日期以检查用户是否输入了过去的日期。 If the entered date is a past date, then I need to print a warning message to enter a valid date in future period.
如果输入的日期是过去的日期,那么我需要打印一条警告消息以在以后的期间输入有效的日期。
I accept input date field in following HTML
code: 我接受以下
HTML
代码中的输入日期字段:
<input size="12" id="inputField" name="inputField" autofocus="" type="date" oninput="return dateValidate(inputField)"/>
My Javascript function to validate input date is: 我用来验证输入日期的Javascript函数是:
<script type="text/javascript">
function dateValidate(inputField)
{
var v2 = document.getElementById('inputField');
var pickeddate = new Date(v2.Value);
todayDate = new Date();
if(pickeddate > todayDate){
return true;
} else {
alert("Enter a valid Date");
}
}
But this code doesn't seem to be working. 但是这段代码似乎没有用。 I want this Javascript function to be run when I enter a past date in the
<input>
field and tab out. 我希望在
<input>
字段中<input>
过去的日期并跳出时运行该Javascript函数。 I want to validate date when it is entered in the field, not when the form is submitted. 我想在字段中输入日期而不是在提交表单时验证日期。
It is not working since there is a issue in your code, just replace this: 由于您的代码中存在问题,因此无法正常工作,只需将其替换:
var pickeddate = new Date(v2.Value);
with this: 有了这个:
var pickeddate = new Date(v2.value); // 'value' should be in lower case
Since, it was not correct, the pickeddate
was always undefined
and code didn't worked. 因为这是不正确的,所以
pickeddate
始终是undefined
,因此代码无效。
You may try this 你可以试试这个
HTML HTML
<input size="12" id="inputField" name="inputField" autofocus="" type="date" onblur="return dateValidate(this)"/>
JS JS
function dateValidate(inputField)
{
var pickeddate = new Date(inputField.value);
var todayDate = new Date();
if( pickeddate > todayDate )
{
return true;
}
else
{
alert("Enter a valid Date");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.