How to: Test Validity Programmatically for ASP.NET Server Controls
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.
By default, ASP.NET Web pages automatically validate that malicious users are not attempting to send script or HTML elements to your application. For more information, see.
You can test for a general, page-wide state, and you can test the state of individual controls. Typically, you do these things in the event handlers that you create for a page.
To test for a general error state
In your code, test the page'sproperty. 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.
Validation information is not available during a page's initialization or load stage. However, you can call themethod manually during Page_Load and then test the page's IsValid property. For details about page states, see .
The following code example shows the event handler for a button. The code tests the page's IsValid property. Note that there 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.
To test for the error state of individual controls
Loop through the page'scollection, which contains references to all the validation controls. You can then examine the IsValid property of each validation control.
If you want to perform this check during Page_Load, you must manually call themethod first.
The following code example shows how you can get the state of individual validation controls.