Javascript - 日期范围验证

2022-01-24 00:00:00 date range javascript

我有一个表单用户可以输入任何日期,但我想设置一个日期范围验证.例如:从 2012 年 1 月 12 日到 2013 年 1 月 1 日,系统无法接受来自用户的任何不在该范围内的日期.我试过这个 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 ..

这是我的表格的一部分:

this is part of my form :

 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 时间戳,现在你从值中得到的第一个日期是一个字符串,你可以't 将其与日期对象进行比较?

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

相关文章