RequiredFieldValidator not working programmatically

1.8k views Asked by At

As the title says. What could be amiss?

I have a regular TextBox on my page - <asp:TextBox ID="tb" runat="server" />

The following works:

<asp:RequiredFieldValidator ID="r" runat="server" ControlToValidate="tb" ErrorMessage="error" />

The following does not work:

RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ID = "rfv";
rfv.ControlToValidate = tb.ID;
rfv.ErrorMessage = "error";
1

There are 1 answers

0
Muhammad Akhtar On BEST ANSWER

you need to add your required field validator

RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ID = "rfv";
rfv.ControlToValidate = tb.ID;
rfv.ErrorMessage = "error";
yourFormId.Controls.Add(rfv);// you need to add this