[英]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.