2014-01-12 81 views
0

我有一個jsp頁面,用戶選擇兩個日期。我需要驗證此日期以確保第一個日期不低於今天的日期。這是我使用的腳本:JSP日期驗證

var todaysDate = new Date(); 

if(document.frm.rentedOnDate.value < todaysDate) 
{ 
    alert("Rented date should not be before today"); 
    document.frm.bank.focus(); 
    return false; 
} 

if(document.frm.rentedOnDate.value> document.frm.returnDate.value) 
{ 
    alert("Return date should be after rented date"); 
    document.frm.bank.focus(); 
    return false; 
} 

這些日期選擇字段:

<p>Select Rental Date: &nbsp;<input type="date" name="rentedOnDate"> </p> 
<p>Select Return Date: &nbsp;<input type="date" name="returnDate"> </p> 

當用戶輸入這是租來的日期,但第一前返回日期第二個腳本功能的工作原理功能不起作用。任何想法爲什麼?

回答

1

你的第二個測試是比較字符串,所以我不會指望它是完全可靠的(前面的零可能會打破它)。

您需要將字符串(.value字段)轉換爲正確的日期對象,然後進行比較。這將解決你的第一次檢查,並改善你的第二次檢查。

此函數將解析以「yyyy-mm-dd」方式提供的日期(可選的2位數年份產生20xx)。 null返回無效日期。

function getDate(str) 
{ 
    var dateParts = /^(\d\d(?:\d\d)?)-(\d\d?)-(\d\d?)$/.exec(str); 
    if (dateParts === null) 
    { 
     return null; 
    } 
    var year = parseInt(dateParts[1]); 
    if (year < 100) 
    { 
     year += 2000; 
    } 
    var month = parseInt(dateParts[2]) - 1; 
    var day = parseInt(dateParts[3]); 
    var result = new Date(year, month, day); 
    return year === result.getFullYear() 
      && month === result.getMonth() 
      && day === result.getDate() ? result : null; 
} 
+0

我用這樣:var D1 =新的日期(document.frm.rentedOnDate)和它的工作!感謝 –

-1
function validateDate(dates){ 
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;  
    var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31); 

    if(regs = dates.match(re)) { 
     // day value between 1 and 31 
     if(regs[1] < 1 || regs[1] > 31) {      
      return false; 
     } 
     // month value between 1 and 12 
     if(regs[2] < 1 || regs[2] > 12) {       
      return false; 
     } 

     var maxday=days[regs[2]-1]; 

     if(regs[2]==2){ 
      if(regs[3]%4==0){ 
       maxday=maxday+1;         
      } 
     } 

     if(regs[1]>maxday){ 
      return false; 
     } 

     return true; 
    } else { 
     return false; 
    }      
} 
+0

上述函數將處理所有情況。 –