如何在用户控件上应用验证?

时间:2012-12-07 06:50:07

标签: asp.net

我有一个ascx文件,我在其中放置了以下代码:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<asp:TextBox ID="textboxDate" runat="server" CssClass="FieldValue" MaxLength="10"
Columns="12" autocomplete="off" Style="padding-right: 18px; border: 1px solid #567890;" />
<ajaxToolkit:CalendarExtender ID="calendarExtenderDate" runat="server" TargetControlID="textboxDate"
PopupButtonID="textboxDate" />

<asp:RequiredFieldValidator runat="server" Enabled="false" ControlToValidate="textboxDate"
ID="valRequired" ErrorMessage="* This field is required" EnableClientScript="true"
Display="Dynamic" Text="*" />

<asp:CompareValidator runat="server" CssClass="error" ControlToValidate="textboxDate"
Operator="DataTypeCheck" Display="Dynamic" Type="Date" ID="valValidDate" ErrorMessage="* Date is in an incorrect format"
Text="*" EnableClientScript="true" />


<asp:CustomValidator CssClass="error" Text="*" runat="server" ID="rangeVal" Display="dynamic" OnServerValidate="rangeVal_Validate" />

我通过

在我的一个表单中调用此用户控件
 <uc:DateControl ID="dateControlStart" runat="server" RequiredErrorMessage="please enter date" />

所以,我想如果用户选择任何小于或等于当前日期的日期,则错误应该是“错误的错误”。我想在客户端的aspx页面中进行此验证,而不是在用户控制中。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

<asp:CustomValidator ID="uxDateFormatValidator" runat="server" ControlToValidate="dateControlStart$textboxDate"
Display="Static" ErrorMessage="Error" ClientValidationFunction="ValidateDateAgainstMinDate"
 />

 function ValidateDateAgainstMinDate(oSrc, args) {
var dateParts = args.Value.split('.');// which separator do you use?
if (dateParts.length >= 3) {
    var day = dateParts[2];
    var month = dateParts[1] - 1; //this one rocks
    var year = dateParts[0];
    var date = new Date(year, month, day);
    var minDate = new Date(1900, 0, 1); // use just new Date(); for today
    args.IsValid = date >= minDate
        && date.getDate() == day
        && date.getMonth() == month
        && date.getFullYear() == year;
}
else {
    args.IsValid = false;
}

}

CustomValidator必须与您的uc:DateControl

一起插入您的页面