ASP.NET: aggregating validators in a user control

Posted by orsogufo on Stack Overflow See other posts from Stack Overflow or by orsogufo
Published on 2010-03-16T16:45:50Z Indexed on 2010/03/16 17:01 UTC
Read the original article Hit count: 431

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about c#