This tutorial will teach you how to use the ValidationGroup property introduced in ASP.NET 2.0, which allows you to link validators to buttons, so that certain buttons in a form can only trigger certain validators.
Validation groups represent something new, introduced in ASP.NET 2.0. With this feature you can implement validation on groups of controls. Before ASP.NET 2.0, when submitting a form, all the controls on the page were being validated. So when you press the Submit button, each and every TextBox or other control that has a validator, was checked. However, this caused a problem when you had multiple forms on a page, with two or more submit buttons. Pressing one of the buttons would start to validate all the controls on a page, and that’s not what we wanted.
So let’s see how these validation groups work. Start a new Web Site in Visual Studio 2005:
Add two panels to the form and some TextBoxes in both. For each TextBox add a validator, I added RequiredFieldValidators because they are the most common ones. Also, add a button in each of the panel, so that our WebForm looks something like:
Be sure to set each validator to validate one of the TextBoxes. You can do this by setting the ControlToValidate property in the Properties window.
After each TextBox has its RequiredFieldValidator, compile and run the web application. Type something into the TextBoxes in Panel2 and leave the TextBoxes in Panel1 blank, because we are not interested in that form. Press the submit button (the second one, of course), and watch the result:
Bummer! Even though we pressed the second button, the validators in the first form reacted and the form didn’t get submitted.
where the validation groups come in handy. Click the first button and in the Properties window scroll to the ValidationGroup property and give it a name, Form1:
Now do the same thing for the second button, set the ValidationGroup property to Form2.
We’re not done yet. The RequiredFieldValidators also have a ValidationGroup property, we need to set this property of the RequiredFieldValidators from Panel1 to the same name we gave the submit button in Panel1: Form1. Same thing needs to be done for the validators in Panel2, set their ValidationGroup property to the same name as the second button: Form2. This way each button is linked to the validators it should fire when it is pressed.
You can compile and run the web application now.
As you can see in the screenshot above, clicking the first button will now fire only the validators that are grouped with that button.