Validation controls test user input, set error states, and generate error messages. They do not change the processing flow of the page, for example, they do not skip code when a user input error is detected. Instead, you'll test the control's state in code before executing your application's specific logic. If an error is detected, your own code will not run; the page will continue processing and be returned to the user with an error message.
Security Note: By default, ASP.NET web pages automatically verify whether a malicious user attempts to send script or HTML elements to your application.
You can test the general page-wide state, and you can test the state of individual controls. Typically, you do this in the event handler you create for the page.
1. Test common error status
In your code, test the page's IsValid property. This property will accumulate the value of the IsValid property of all validation controls on the page (using logical AND). If any validation control is set to invalid, the page's property will return false.
Description: Authentication information is not available during the initialization or loading phase of the page. However, you can manually call the Validate method during Page_Load and then test the page's IsValid property.
The following code example demonstrates an event handler for a button. This code tests the page's IsValid property. Note that no other clauses are needed here because the page will automatically return to the browser and the validation control will display its own error message.
void Button1_Click(object sender, System.EventArgs e)
{
if(IsValid)
{
// Perform database updates or other logic here.
}
}
2. Test the error status of individual controls
Work through the page's Validators collection, which contains references to all validation controls. You can then check the IsValid property of each validation control.
Note: If you want to perform this check during Page_Load, you must first call the Validate method manually.
The following code example demonstrates how to obtain the state of a single validation control.
if (this.IsPostBack)
{
this.Validate();
if (!this.IsValid)
{
string msg = "";
// Loop through all validation controls to see which
// generated the errors.
foreach (IValidator aValidator in this.Validators)
{
if (!aValidator.IsValid)
{
msg += "<br />" + aValidator.ErrorMessage;
}
}
Label1.Text = msg;
}
}
This article comes from the CSDN blog. Please indicate the source when reprinting: http://blog.csdn.net/dodream/archive/2009/12/17/5024643.aspx
-