views:

299

answers:

2

Hi,

I don't know whether this is really possible, but I'm trying my best.

If I have a (complex) custom server control which (beside other controls) renders a TextBox on the UI. When placing the server control on a page, would it be possible to attach a RequiredField validator to that server control, such that the validator validates the Text property of that control which points to the Text property of the rendered TextBox?

Of course I could incorporate the RequiredField validator directly into the server control, but this is for other reasons not possible (we are rendering RequiredField validators automatically on the UI).

Thanks for your help.

A: 

I think one solution is to put your TextBox control inside a Panel then you add the RequiredValidator control dynamically on 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 assure that the validation controle place is correct when added

Marwan Aouida
hmm...i was looking more for something like annotating the server control in order to tell the validator which property has to be validated...
Juri
A: 

I got it, the 2nd time that I'm answering to my own post :) Next time I'll do a deeper research before.

For those of you that may encounter the same problem. You have to specify the ValidationProperty attribute on your server control's class. For instance if your server control exposes a property "Text" which is displayed to the user and which should also be validated, you add the following:

[ValidationProperty("Text")]

Then it should work.

Juri