views:

115

answers:

1

I have several server controls that implement the IValidator interface. As such, they have their own Validate() methods that look like this.

public void Validate()
{
  this.IsValid = true;
  if (someConditionFails())
  {
    ErrorMessage = "Condition failed!";
    this.IsValid = false;
  }
}

I understand that these Validate() methods are executed on postback before the load completed event that is executed before the save button's event handler. What I would like to do is pass in a reference to an instance of a custom class that collects all the error messages that I can access from Save button event handler.

In other words, I would like to do something like this:

public void Validate(ref SummaryOfErrorMessages sum)

I guess I can't do this as the signature is different from what the IValidator interface has. The other option I can think of is on Load Completed event, I would iterate through all the validators on page, get the ones with IsValid = false and create my SummaryOfErrorMessages there. Does this sound right? Is there a better way of doing it?

+1  A: 

I'd iterate through all the validators on the page after validation has been performed and get the summary. You can find all the validators from Page.Validators.

As a warning, please note that validators that only use IValidator and don't inherit from BaseValidator do not support validation groups at all, so it would seem that not inheriting from BaseValidator is somewhat deprecated. I have been bitten by this once.

Matti Virkkunen
@Matti - Thanks for the note on validation groups. I created a overriden Page.Validate that not only grabs BaseValidators but also IValidators. So all's good.I guess I have to do something like Page.Validators[x].IsValid and then add the messages accordingly. Somehow, it feels like a hack. I would somehow want to add all the messages in the individual IValidators