I have a user control with some custom client side validation. When I have the user control on a page, it works no problem. But if that page has a postback event (select a certain option from a dropdown, and more fields are displayed), my validation no longer seems to work. My validation is as follows:
protected void Page_Load(object sender, EventArgs e)
{
Type cstype = this.GetType();
if (!Page.ClientScript.IsStartupScriptRegistered(cstype, "ValidatorType"))
{
String DateValidator;
DateValidator = "<script type=\"text/javascript\">\n";
DateValidator += "function ValidateDate(source, args) {\n";
DateValidator += " var ddDay = document.getElementById(source.day);\n";
DateValidator += " var day = ddDay.selectedIndex;";
DateValidator += " var ddMonth = document.getElementById(source.month);\n";
DateValidator += " var month = ddMonth.selectedIndex;\n";
DateValidator += " var ddYear = document.getElementById(source.year);\n";
DateValidator += " var year = ddYear.selectedIndex;\n";
DateValidator += " if (day == 0 || month == 0 || year == 0)\n";
DateValidator += " args.IsValid = false;\n";
DateValidator += " else\n";
DateValidator += " args.IsValid = true;\n";
DateValidator += " }\n";
DateValidator += "</script>";
Page.ClientScript.RegisterStartupScript(cstype, "ValidatorType", DateValidator);
}
Page.ClientScript.RegisterExpandoAttribute(reqDueDate.ClientID, "month", ddMonth.ClientID);
Page.ClientScript.RegisterExpandoAttribute(reqDueDate.ClientID, "day", ddDay.ClientID);
Page.ClientScript.RegisterExpandoAttribute(reqDueDate.ClientID, "year", ddYear.ClientID);
}
I’m stumped. Any advice?
EDIT:
Here is the User Control that I am using.
<asp:DropDownList ID="ddMonth" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="">--Month--</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddDay" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="">--Day--</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddYear" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="">--Year--</asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="reqDueDate" EnableClientScript="true" ClientValidationFunction="ValidateDate" runat="server" ErrorMessage="Required" CssClass="input-notification error png_bg" Display="Dynamic"></asp:CustomValidator>
Turns out, I needed to do 2 things. Put an Update Panel around in my user code, and change the lines
to
Thanks all for your help and http://www.aspnetajaxtutorials.com/2010/09/customvalidator-registerexpandoattribut.html for the guidance.