asp.net.ph

Skip Navigation Links

Testing Validity Programmatically

ASP.NET Web Forms   Web Forms Server Controls   Web Forms Validation


Validation controls test user input, set an error state, and produce error messages. They do not change the flow of page processing — for example, they do not bypass your code if they detect a user input error. Instead, you test the state of the controls in your code before performing application-specific logic. If you detect an error, you prevent your own code from running; the page continues to process and is returned to the user with error messages.

You can test for a general, page-wide state, and you can test the state of individual controls. Typically, you do this in the event-handling methods that you create for a page.

NOTE: Validation information is not available during a page’s initialization or load stage. For details about page states, see Web Forms Page Processing Stages.

To test for a general error state

  • In your code, test the page’s IsValid property. This property rolls up the values of the IsValid properties of all the validation controls on the page ( using a logical AND ); if any one validation control is set to invalid, the page’s property will return false.

    The following example [ Visual Basic ] shows the event-handling method for a button. The code tests the IsValid property of the entire page ( whose class name is WebForm1 ) . Note that this is no need for an Else clause, because the page will be returned automatically to the browser and the validation controls will display their own error messages.

Protected Sub Button1_Click ( ByVal sender as Object, _
      ByVal e as EventArgs )
   If WebForm1.IsValid then
      ' Perform database updates or other logic here
   End If
End Sub

To test for the error state of individual controls

  • Loop through the page’s Validators collection, which contains references to all the validation controls whose status has changed since the last round trip. You can then examine the IsValid property of each validation control.

    The following example shows how you can get information about individual validation controls.


if ( !Webform1.IsValid ) {
   // loop through all validation controls to see which generated the error ( s ) 

   for ( i = 0; i < validators.length; i++ ) {
      if ( !Validators [ i ].IsValid ) {
         // code your error message here 
         // this is one that produced an error
      }
   }
}
  C# VB

See Also

Data Entry Validation ( Client-Side )



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note