0
votes

I am developing a web application where I would like to perform a set of validations on a certain field (an account name in the specific case).
I need to check that the value is not empty, matches a certain pattern and is not already used.
I tried to create a UserControl that aggregates a RequiredFieldValidator, a RegexValidator and a CustomValidator, then I created a ControlToValidate property like this:

public partial class AccountNameValidator : System.Web.UI.UserControl {
    public string ControlToValidate {
        get { return ViewState["ControlToValidate"] as string; }
        set { 
            ViewState["ControlToValidate"] = value;
            AccountNameRequiredFieldValidator.ControlToValidate = value;
            AccountNameRegexValidator.ControlToValidate = value;
            AccountNameUniqueValidator.ControlToValidate = value;
        }
    }
}

However, if I insert the control on a page and set ControlToValidate to some control ID, when the page loads I get an error that says Unable to find control id 'AccountName' referenced by the 'ControlToValidate' property of 'AccountNameRequiredFieldValidator', which makes me think that the controls inside my UserControl cannot resolve correctly the controls in the parent page.

So, I have two questions:

1) Is it possible to have validator controls inside a UserControl validate a control in the parent page?

2) Is it correct and good practice to "aggregate" multiple validator controls in a UserControl? If not, what is the standard way to proceed?

2

2 Answers

1
votes

Addressing your second question first- I don't think it's a good idea to "aggregate" validators together this way unless you include the controls you're validating in the user control. Too much work for not enough payoff.

You could fix this problem by exposing properties on your AggregatedValidator to set the names of the controls to validate, and pass in the ClientID of those controls you want validated.

1
votes

I believe ASP.NET expects the ControlToValidate ID to be in the same naming container. You can probably override the validation method and use Parent.FindControl.

EDIT: This might be a good place to use a CompositeControl rather than a UserControl. They are designed for just this kind of aggregation. But you might have a similar NamingContainer issue.