Javascript - 日期范围验证 [英] Javascript - date range validation

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

问题描述

我有一个表单用户可以输入任何日期,但我想设置一个日期范围验证。例如:从1-12-2012到1-1-2013,系统不能接受来自不在范围内的用户的任何日期..我尝试过这个JavaScript代码,但它甚至不给我任何警报甚至日期不在范围内。

i've a form user can enter any date , but i want to set a date range validation . for example: from 1-12-2012 to 1-1-2013 and the system can't accept any date from user that not in the range.. i've tried this javascript code but it doesn't give me any alert even when date not in range ..

这是我表单的一部分:

 echo "<tr><th bgcolor='FF6600'> Date <font size='4' color='red'>* </font></th>
        <td> <input type='date' name='v2' value=''   ></td></tr>";


echo "<tr><th bgcolor='FF6600'> Time <font size='4' color='red'>* </font></th>
        <td> <input type='time' name='v3' value=''   ></td></tr>";

        echo "<tr><th bgcolor='FF6600'> Place <font size='4' color='red'>* </font></th>
        <td> <input type='text' name='v4' value=''   ></td></tr>";

这是JavaScript代码

and this is the javascript code

    <script language="javascript">

    function validation(form)
 {

 var v2 = document.getElementById('v2');
 var date = v2.value;
 if ( (v2 > new date('12/12/2012')) && 
    (v2 < new date('1/1/2013')) ){
    // date is in your valid range
     return true;
} else {
    // date is not in your valid range

    alert("date is not in valid range")
    return false;
}


}

    </script>


推荐答案

要比较日期,您应该使用unix时间戳,现在您从该值获得的第一个日期是一个字符串,您不能与日期对象进行比较?

To compare dates, you should be using the unix timestamp, and right now the first date you're getting from the value is a string, and you can't compare that against date objects?

确保您有时间戳unix时间,然后比较:

Make sure you have timestamps in unix time, and then compare those:

function validation(form) {
    var v2 = document.getElementById('v2'),
      date = new Date(v2.value),
      d1   = date.getTime(),
      d2   = new Date('12/12/2012').getTime(),
      d3   = new Date('1/1/2013').getTime();

   if (d1 > d2 || d1 < d3) {
       return true;
   }else{
       alert("date is not in valid range")
   }
}

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

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