[英]jQuery - Get value of .NET RequiredFieldValidator “ControlToValidate”
[英]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
設置EndDate
的maxDate
,但是這樣做有兩個基本問題。
DateTime.AddMonths()
函數。 因此,我想我將只使用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.