2013-07-17 118 views
0

我正在尝试在不使用正则表达式的情况下编写javascript日期格式验证。当我输入的日期26/02/2013我有周三的2093年9月2日的警戒值和错误消息的日期不是有效的格式使用正则表达式验证日期格式

任何帮助将欣赏

function CheckDateFormat(StartDateform)  

    { 
      var StartDateform= document.getElementById('tblTarget').rows[1].cells[StartDate].getElementsByTagName('input')[0].value;   
      spl = StartDateform.split("/"); 


      var testDate=new Date(spl[2],spl[0]-1,spl[1]);    

      year= testDate.getFullYear();     
      month = testDate.getMonth()+1;     
      day= testDate.getDate(); 

      alert ("the date value is "+ " "+ testDate); 

     if (day!==spl[1] || month!==spl[0] || year!==spl[2])      
     { 
      alert ("the date value is "+ " "+ testDate); 
      alert(StartDateform + " " + "Is an Invalid Date. Please use the format 'MM/DD/YYYY'"); 
      return false; 
     } 


     return true;       
    }     

    function Submit() 
    { 
     if(CheckDateFormat()) 
     { 
     $('button_submit').click(); 
     alert('New rate submitted'); 
     } 
    } 
+1

为什么没有正则表达式?正则表达式对于这类事情来说非常棒。 – rjmunro

+0

只是为了您的信息,存在一些非常成熟的JS库,它们在解析日期方面做得很好,比如** http://momentjs.com/**。 – thmshd

+1

@rjmunro regexp对验证日期不利,因为您还需要验证很多无效日期,f.ex闰年和日历中的其他违规行为。 – David

回答

1

Date constructor预计Y/M/d:

Date - 创建JavaScript的Date实例这让你 日期和时间工作。

语法

new Date();
new Date(value);
new Date(dateString);
new Date(year, month, day [hour, minute, second, millisecond]);

如果日期为26/02/2013,你与喂养它Y/d-1/M:

new Date(spl[2],spl[0]-1,spl[1]); 

从一天开始抽象1没有任何意义,所以我猜你刚刚搞混了索引。