Handling RequiredFieldValidator inside of a User Control

Kyle picture Kyle · Jan 28, 2011 · Viewed 8k times · Source

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
    }

Answer

PMC picture PMC · Jan 28, 2011

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;}
    }

 }