簡體   English   中英

通過jQuery更新ControlToValidate的值時,導致ASP.NET RangeValidator觸發

[英]Cause an ASP.NET RangeValidator to fire when the value of the ControlToValidate is updated via jQuery

我有一組日期范圍控件:

<div id="CustomDateRow" class="row-fluid" runat="server">
    <label class="span2 FieldLabel">
        Start Date:
    </label>
    <asp:TextBox ID="StartDate" CssClass="datepicker span3" runat="server" ClientIDMode="Static"></asp:TextBox>
    <label class="span2 FieldLabel">
        End Date:
    </label>
    <asp:TextBox ID="EndDate" CssClass="datepicker span3" runat="server" ClientIDMode="Static"></asp:TextBox>
</div>

我正在將這些控件轉換為jQuery UI日期選擇器。

我需要確保用戶在任何給定時間不能選擇超過30天。 最初,我計划在設置StartDate設置EndDatemaxDate ,但是這樣做有兩個基本問題。

  1. JavaScript中沒有類似的好的DateTime.AddMonths()函數。
  2. 這篇SO文章使我意識到,它確實不那么用戶友好。

因此,我想我將只使用RangeValidator並在每次值更改時驗證兩個日期之間的天數。

因此,我有一個RangeValidator像這樣:

<div class="row-fluid">
    <asp:RangeValidator ID="DateRangeValidator" runat="server" ControlToValidate="DateRange"
        ErrorMessage="The date range must be at least one day and not more than thirty."
        EnableClientScript="true" MinimumValue="1" MaximumValue="30" CssClass="errortext span9 offset2"
        Display="Dynamic" />
</div>

並且它正在驗證基本的文本輸入控件:

<asp:TextBox ID="DateRange" runat="server" ClientIDMode="Static" />

日期更改時在JavaScript中更新的內容:

$('.datepicker').change(function () {
    var nDifference = Math.abs(new Date($('#StartDate').val()) - new Date($('#EndDate').val()));
    var one_day = 1000 * 60 * 60 * 24;
    $('#DateRange').val(Math.round(nDifference / one_day));
});

問題

即使當我通過jQuery設置值時確實更改了該值, RangeValidator也沒有反應。 但是,如果我在文本輸入中鍵入該值並將其保留, RangeValidator按預期工作。

我是否需要在DateRange控件上觸發某種事件以強制RangeValidator執行?

好吧,我最終做了兩個非常簡單的事情來解決這個問題,並且所有這些問題都駐留在JavaScript方法中以計算范圍。 這是工作代碼。

$('.datepicker').change(function () {
    var nDifference = new Date($('#EndDate').val()) - new Date($('#StartDate').val());
    var one_day = 1000 * 60 * 60 * 24;
    $('#DateRange').val(Math.round(nDifference / one_day));
    Page_ClientValidate(null);
});

請注意,在nDifference計算中我擺脫了Math.abs ,因為我需要真正的差異,即正數或負數。 最后,請注意,我添加了行Page_ClientValidate(null); ,這就是導致我設置的RangeValidator進行驗證的原因。

完美的作品!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM