要求用户可以在文本框中输入日期或选择带日历的日期。我使用一个文本框,其中用户输入日期和范围验证器(类型是日期)来验证用户的输入,日历扩展器作为日历,以及一个弹出日历的按钮。当用户输入两位数年份(如9/24/11)时,rangvalidator认为是有效日期,但是当我点击按钮时,今天会显示日历扩展器。如何让日历扩展程序跳转到更正日期(2011年9月24日)?
以下是代码:
<div style="display:inline-table">
<div style="vertical-align:middle">
<asp:TextBox ID="txtDateTime" runat="server" CssClass="calInput" MaxLength="10" placeholder="MM/dd/yyyy"></asp:TextBox>
<asp:ImageButton ID="imgBtnShowCalendar" runat="server"
CssClass="calInput calImg" ImageUrl="~/images/calendar.gif"
onclick="imgBtnShowCalendar_Click" />
</div>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" Animated="false" Format="MM/dd/yyyy" TargetControlID="txtDateTime" PopupButtonID="imgBtnShowCalendar">
</cc1:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtDateTime" Display="Dynamic"
ErrorMessage="RequiredFieldValidator" Font-Names="Arial" Font-Size="12px"
ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" MinimumValue="1/1/1900"
MaximumValue="6/6/2079" Type="Date" ControlToValidate="txtDateTime"
runat="server" ErrorMessage="RangeValidator" Display="Dynamic"
Font-Names="Arial" Font-Size="12px" ForeColor="Red"></asp:RangeValidator>
</div>
答案 0 :(得分:1)
来自http://forums.asp.net/t/1391032.aspx的解决方案是添加客户端功能来解决此问题。您应该使用MaskedEditExtender
添加MaskedEditValidator
并设置ClientValidationFunction
。您还可以将ClientIDMode
fileld的txtDateTime
属性设置为Static
。
<div style="display:inline-table">
<%-- ... --%>
<asp:TextBox ID="txtDateTime" runat="server" ClientIDMode="Static" CssClass="calInput" MaxLength="10" placeholder="MM/dd/yyyy"></asp:TextBox>
<%-- ... --%>
<%-- all yours previous code goes here --%>
<script type="text/javascript">
function FixCentury(sender, args) {
// the current value is saved as args.Value;
// you can modify the method of changing the value yourself.
var year = args.Value.split("/")[2];
if (year.substr(0, 2) == "00") {
var newyear = "20" + year.substr(2, 2);
document.getElementById("txtDateTime").value = args.Value.substr(0, 6) + newyear;
}
}
</script>
<cc1:MaskedEditExtender ID="MaskedEditExtender1" runat="server" TargetControlID="txtDateTime"
MaskType="Date" Mask="99/99/9999" Century="2100" AutoComplete="true">
</cc1:MaskedEditExtender>
<cc1:MaskedEditValidator ID="MaskedEditValidator1" runat="server" ControlExtender="MaskedEditExtender1"
ControlToValidate="txtDateTime" IsValidEmpty="false" InvalidValueMessage="Check date!"
InvalidValueBlurredMessage="Check date!" Display="Dynamic" ClientValidationFunction="FixCentury" />
</div>