I am facing an issue with the client-side validation in my user control. Everything works fine when the user control is placed on a page, but if there is a postback event (like selecting an option from a dropdown that displays more fields), the validation stops working. Below is the code for my validation logic:
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 need help figuring out why the validation fails during postback events.
EDIT:
Below is the code snippet of the User Control 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>