无法完全使日期正确无效/验证(到达日期)



这是我的html代码,其中包含一段代码,我试图用来使日期条目无效/验证,希望声明所有相应的和必要的变量。

       <html>
       <head>
       <title> Booking Page </title>
       <script>
       function Booking(){
        var departuredate = document.getElementById("departdate").value; //departure date selected by user
        var arrivaldate = document.getElementById("arrivedate").value; //arrival date selected by user
        departuredate = new Date(departuredate);
        arrivaldate = new Date(arrivaldate); 
        CurrentDate = new Date(); //todays date
                month = '' + (arrivaldate.getMonth() + 1),
                day = '' + arrivaldate.getDate(),
                year = arrivaldate.getFullYear();
                var adate = [day, month, year].join('/');
                alert(adate);
日期

仅适用于抵达日期。我计划在出发日期正确后复制和调整代码。目前,该代码似乎使所有条目无效,不允许验证完全有效的条目。

         var re = /[0-9]{2}/[0-9]{2}/[0-9]{4}/;
         if (!adate.match(re))
         {
            document.getElementById("temp").innerHTML = "Incorrect format"
            document.MyForm.arrivedate.focus();
            document.getElementById("arrivedate").style.border='1px solid red';
            return false;
          } 
          else 
          {
            // if none of the above situaton's occur then the input is true and validated
            alert('Dates are validated');
            return true;          
           }
           }
           </script>
           </head>
           <body>
           <H1> Booking Form </H1>
          <Form action="testpage.py" method="POST" name="MyForm" onsubmit="return Booking()">

            <p>Departure Date:</p>
            <input type=date name="departdate" id="departdate" > 
            <p>Arrival Date:</p>
            <input type=date name="arrivedate" id="arrivedate">
            <input type=submit value="Find flights">
           </Form>        
           </body>
           </html>

您在这里遇到多个问题。首先,输入的日期类型是非标准的,因此在大多数浏览器中都不起作用(IIRC chrome,edge和iOS safari是例外)。

如果您必须支持桌面 safari(不支持模式属性),我建议您使用第三方库(如 jquery-ui-datepicker),或者使用 html pattern 属性或 js 事件处理程序使用带有验证逻辑的文本输入。

<input type="text" pattern="/[0-9]{2}/[0-9]{2}/[0-9]{4}/"...

或者,如果模式不起作用:

var myDateInput = document.getElementById('date-input');
myDateInput.addEventListener('change', function(e) {
  if (!(e.target.value.match(dateRegex)) {
    //let user know somehow
  }
});

您可以限制处理程序,使其不会在连续击键时触发。另请注意,即使在具有日期输入类型的浏览器中,他们也希望使用"yyyy-mm-dd"格式,因此请制作正则表达式:

/[0-9]{4}-[0-9]{2}-[0-9]{2}/ .

最新更新