Bind RequiredValidator to custom TextBox render server control

I don't know if this is actually possible, but I am trying my best.

If I have a (complex) custom server control that (among other controls) renders a TextBox in the UI. When placing a server control on a page, could a RequiredField validator be bound to that server control so that the validator checks the Text property of that control, which points to the Text property for the TextBox?

Of course, I could include the RequiredField validator directly in the server control, but that is not possible for other reasons (we automatically handle RequiredField validators in the UI).

Thank you for your help.

-1


source to share


2 answers


I realized the second time when I reply to my post :) Next time I will do deeper research earlier.

For those of you who may be facing the same problem. You must specify the attribute ValidationProperty

in your server management class. For example, if your server control exposes a "Text" property that is displayed to the user and must also be checked, you add the following:



[ValidationProperty("Text")]

      

Then it should work.

0


source


I think one solution is to put your TextBox control inside the panel and then add the RequiredValidator element dynamically to the Page_Load event handler.

<asp:Panel ID="Panel1" runat="server">
 <MyCustomTextBox ID="TextBox1" runat="server"></MyCustomTextBox>
 </asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Button" />

      

then



protected void Page_Load(object sender, EventArgs e)
        {
            var validator = new RequiredFieldValidator();
            validator.ControlToValidate = "TextBox1";
            validator.ErrorMessage = "This field is required!";
            Panel1.Controls.Add(validator);

        }

      

I put the CustomTextBox inside the panel to make sure the validation control location is correct when adding

+1


source







All Articles