Custom Control referenced by 'RequiredFieldValidator' cannot be validated

Soroush Hakami picture Soroush Hakami · May 12, 2011 · Viewed 8.3k times · Source

Question: How do I correctly extend a custom control to work with the RequiredFieldValidator? I've read this, but trying to implement it didn't solve the problem for me. This is what I've come up with so far:

 <%@ Register src="DynamicGenerator/Controls/ReferenceControl.ascx" tagname="ReferenceControl" tagprefix="uc1" %>
    <uc1:ReferenceControl ID="SelectAgreement" runat="server" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator" ControlToValidate="SelectAgreement" runat="server" ErrorMessage="Select an agreement!"></asp:RequiredFieldValidator>

Code behind:

[ValidationProperty("ConceptDefinitionId")]
public partial class ReferenceSelector : System.Web.UI.UserControl, IReference
{
   //lots of other stuff
 public string ConceptDefinitionId
        {
            get { return ReferenceControl.ConceptDefinitionId ?? ""; }
            set { ReferenceControl.ConceptDefinitionId = value; }
        }
}

Loading this page gives me the following error:

Control 'SelectAgreement' referenced by the ControlToValidate property of 'RequiredFieldValidator' cannot be validated.

stacktrace:

[HttpException (0x80004005): Control 'SelectAgreement' referenced by the ControlToValidate property of 'RequiredFieldValidator' cannot be validated.]
   System.Web.UI.WebControls.BaseValidator.CheckControlValidationProperty(String name, String propertyName) +8739685
   System.Web.UI.WebControls.BaseValidator.ControlPropertiesValid() +40
   System.Web.UI.WebControls.BaseValidator.get_PropertiesValid() +21
   System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +27
   System.Web.UI.Control.PreRenderRecursiveInternal() +80
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Control.PreRenderRecursiveInternal() +171
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842

Answer

V4Vendetta picture V4Vendetta · May 12, 2011

You will need to place the RequiredFieldValidator inside the UserControl and validate a specific control like a TextBox or DropDown, since validators are allowed only in the same naming container and in your case the UserControl is a different container so this won't work.

Another way could be using ValidationPropertyAttribute