Xavier Poinas
Xavier Poinas

Reputation: 19743

Web User Controls and Validation

I have an ASP.Net web user control that contains a TextBox and a calendar from the Ajax Control Toolkit.

When I include this user control on my page I would like it to participate in input validation (there is a required filed validator set on the TextBox inside the UC), ie. when the page is validated the content of the UC should also be validated. So I had my UC implement the IValidator interface, which worked well except that I could not set the validation group on the user control. Apparently I'm supposed to inherit from BaseValidator to do that, but I can't since I'm already inheriting UserControl.

There's got to be a way to deal with this common scenario.

Upvotes: 12

Views: 16724

Answers (4)

Sjoerd
Sjoerd

Reputation: 75679

You can reference a control within a user control by seperating the two with a dollar sign:

<asp:RequiredFieldValidator ControlToValidate="MyUserControl$ControlId" runat="server" />

Upvotes: 15

Aleksandar
Aleksandar

Reputation: 1339

Try adding [ValidationProperty("NameOfPropertyToBeValidated") on your user control class.

Upvotes: 3

silverbugg
silverbugg

Reputation: 186

If you are planning to add lots of validation in the future it may pay off to check out Peter Blum's DES (Data Entry Suite) - it has numerous enhanced controls for data entry and validation including conditional validation scenarios and the one you are describing. Licensing is very reasonable compared to the time required to develop it yourself.

Upvotes: 0

Scott Ivey
Scott Ivey

Reputation: 41588

Create a property on your new user control that sets the validation group on the contained validator. Then from your markup, all you need to do is just set the ValidationGroup property on the control, and that'll roll to the validators contained in the user control. You likely don't need the interface or inheriting from BaseValidator unless you are creating JUST a validation user control.

public string ValidationGroup
{
   get
   {
      return MyRequiredFieldValidator.ValidationGroup;
   }
   set
   {
      MyRequiredFieldValidator.ValidationGroup = value;
   }
}

Upvotes: 11

Related Questions