How does Page.IsValid work?

Validation occurs after Page_Load, but before event handlers (See http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx).

If your button does not cause validation, you must manually fire Page.Validate.

You may not interrogate Page.IsValid until after (1) you have called Page.Validate or (2) a control that causes validation was the source of/included in a postback.

If you require validation to occur before event handlers fire, you may use:

if (Page.IsPostback) 
{
   Page.Validate( /*Control Validation Group Name Optional*/ );
   if (Page.IsValid)
   {
       //Do some cool stuff
   }
}

You may also want to consider redesigning so you aren’t required to do so.

In an event handler that handles a control which causes validation, Page.IsValid is guaranteed to be available. In all other cases, it is generally safer to re-request validation. One model for handling submissions on a form that has validators:

void btnSubmit_Click(object sender, EventArgs e)
{
   this.UpdateGUIWithSubmitRequest();
   if (Page.IsValid)
   {
      this.ProcessSuccessfulSubmission();
   }
   else
   {
      this.ProcessInvalidSubmission();
   }
}

If you are using a CustomValidator that has a very expensive validation step, you may consider caching the result in the HttpResponse.Cache so you do not have to re-validate if multiple calls to Page.Validate occur.

void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
   CustomValidator self = (CustomValidator)source;
   string validatorResultKey = self.ClientID;
   bool? validatorResult = Context.Items[validatorResultKey] as bool?;
   if (validatorResult.HasValue)
   {
      args.IsValid = validatorResult.Value;
      return;
   }

   bool isValid = this.DoSomethingVeryTimeConsumingOrExpensive();
   Context.Items[validatorResultKey] = isValid;
   args.IsValid = isValid;
}

This, of course, depends 100% on your architecture and whether or not you are able to assume that a passed/failed validation during initial validation still passes/fails during subsequent validations of the same Page Life Cycle.

Leave a Comment