Handling RequiredFieldValidator inside of a User Control

8.2k views Asked by At

I have a User Control which consists of a TextBox with a few extras, but for purposes of this example just assuming it's a plain TextBox will be sufficient. I am calling this User Control from a Web Form and would like to be able to use a RequiredFieldValidator that basically would function the same as if I used it on a TextBox on the web form. How do I configure my User Control to handle this?

EDIT:

DatePicker.ascx

<asp:TextBox runat="server" ID="myControlTB">

DatePicker.ascx.cs

[ValidationProperty("Text")]
public partial class DatePicker : System.Web.UI.UserControl
{
    public String Text { get { return myControlTB.Text; } set { myControlTB.Text = value; } }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

WebForm.aspx

<cu:UserControl runat="server" ID="myControl">
<asp:RequiredFieldValidator runat="server" errormessage="This is a required field." ControlToValidate="myControl">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />

WebForm.aspx.cs

protected void btnSubmit_Click(object sender, EventArgs e)
{
    Page.Validate();
    if (Page.IsValid)
    {
        // e-mail the form
    }
2

There are 2 answers

5
PMC On BEST ANSWER

You would need to set the ValidationProperty attribute on the control and expose the Textbox Text property as a control property

 [ValidationProperty("Text")]
 public partial class Control
 {
    public string Text 
    {
        get { return textbox.Text;}
    }

 }
1
Brian Mains On

Add a property to the user control:

public string TextBoxID
{
   get { return myControlTB.ClientID; }
}

And then for the validation control, programmably set it from code:

void Page_Load(..)
{
    this.rfv.ControlToValidate = this.uc.TextBoxID;
}

I actually don't know if it will work this way, but you could also try UniqueID, or the ID directly, and see if any of that makes a difference.

Either that, or change TextBoxID to TextboxText, and return myControlTB.Text, and add a [ValidationProperty("TextBoxText")] on the control, and set the ControlToValidate on the required field validator to the user control.

Try one of those approaches,

HTH.