用于验证输入日期的Javascript

用于验证输入日期的Javascript

本文介绍了用于验证输入日期的Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Javascript 编程的新手,我正在尝试验证输入的日期< input> 来自日历片段,该片段是从外部 Javascript 文件中获取的。我正在尝试验证日期以检查用户是否输入了过去的日期。如果输入的日期是过去的日期,那么我需要打印一条警告消息,以便在将来的时间段内输入有效日期。

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. 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.

我接受以下<$中的输入日期字段c $ c> HTML 代码:

<input size="12" id="inputField" name="inputField"  autofocus="" type="date"     oninput="return dateValidate(inputField)"/>

我验证输入日期的Javascript函数是:

My Javascript function to validate input date is:

<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");
 }
}

但这段代码似乎不起作用。我希望在< input> 字段中输入过去的日期并运行Tab键时运行此Javascript函数。我希望在字段中输入日期时验证日期,而不是在提交表单时验证日期。

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. I want to validate date when it is entered in the field, not when the form is submitted.

推荐答案

您可以尝试这个

HTML

<input size="12" id="inputField" name="inputField"  autofocus="" type="date"     onblur="return dateValidate(this)"/>

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");
    }
}

这篇关于用于验证输入日期的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 10:19