2011-05-12 43 views
0

我有一個需求,需要檢查兩個日期選擇器之間輸入的天數之間的驗證[從&到日期]。我的要求是它不應該超過100天。ASP.Net驗證到達和離開天數之間的天數

有沒有一種方法可以用asp.net提供驗證器。我可以繼續爲它(客戶端和服務器端)編寫customvalidator,但是想知道使用CompareValidator還是RangeValidator可以實現?

回答

0

以下功能會怎麼做,如果你在以後類似的找工作還挺回答

 function CheckDateRange(start, end, numberOfDays) { 

     // Parse the entries 
     var startDate = Date.parse(start); 
     var endDate = Date.parse(end); 
     // Make sure they are valid 
     if (isNaN(startDate)) { 
      alert("The start date provided is not valid, please enter a valid date."); 
      return false; 
     } 
     if (isNaN(endDate)) { 
      alert("The end date provided is not valid, please enter a valid date."); 
      return false; 
     } 
     // Check the date range, 86400000 is the number of milliseconds in one day 
     var difference = (endDate - startDate)/(86400000 * numberOfDays); 
     if (difference < 0) { 
      alert("The start date must come before the end date."); 
      return false; 
     } 
     if (difference >= 1) { 
      alert("The range must not exceed 100 days."); 
      return false; 
     } 
     return true; 
    } 

得到幫助從幾分相似post

1

嘗試使用自定義的驗證:

<asp:CustomValidator ID="valCustmCheckDate" runat="server" ErrorMessage="The date difference should not be greater than 100 days" ForeColor="Red" ValidationGroup="LoginUserAdd" ClientValidationFunction="CompareStartAndEndDate"></asp:CustomValidator> 

調用以下javascript中的函數:

function CompareStartAndEndDate(sender,args) { 
    var txtFromExpiryDate = document.getElementById('<%=txtFromDate.ClientID %>');//dd/mm/yyyy format 
    var txtToExpiryDate = document.getElementById('<%=txtToDate.ClientID %>');//dd/mm/yyyy format 

    var a = txtFromDate.value.split('/'); 
    var b = txtToDate.value.split('/'); 

    var FromDate = new Date(a[2], a[1] - 1, a[0]); 
    var ToDate = new Date(b[2], b[1] - 1, b[0]); 

     var newFromDate =FromDate.getTime(); 
     var newToDate=ToDate.getTime(); 

     var dateDiffInMilliseconds= newToDate-newFromDate; 

    var dateDiffInDays=dateDiffInMilliseconds/(1000 * 60 * 60 * 24)  


    if (dateDiffInDays>100) { 
      args.IsValid = false; 
    } 
    else { 
      args.IsValid = true; 
    } 

    } 

希望這會爲你做...

+0

謝謝你的男人。是的,我總是有這種選擇,但想知道是否有人使用Compare或Range Validator進行智能實現。我知道這是不可行的,但有一些真正的智慧:) – DotNetInfo 2011-05-13 02:08:38