Javascript - date range validation

混江龙づ霸主 提交于 2019-12-13 07:38:31

问题


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

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>

回答1:


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?

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



回答2:


You can make a function like this:

function checkMyDateWithinRange(myDdate){
    var startDate = new Date(2012, 11, 1);
    var endDate = new Date(2012, 0, 1);     
    if (startDate < myDate && myDate < endDate) {
       return true; 
    }
   return false;
}

and test any date like calling this function:

var inputDate= document.getElementById('tbDate'),
date = new Date(inputDate.value);
if(!checkMyDateWithinRange(date)){
    alert('Date is not in range!!!');
}

Here is Working Demo



来源:https://stackoverflow.com/questions/13780881/javascript-date-range-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!