Validators and Page Cancellation

While working on a current project with ASP.NET 2.0, I needed to add some validators to a form. Thankfully, ASP.NET has built in range, required and custom (where you write your own Javascript validator) validators. They work really well by including some already made Javascript functions to your page. When you click your submit button for your form, the Javascript validators run and check any fields that need validating.

But wait, what happens if you add another button, or for that matter, any control that performs a post back? Well they all try and validate the form. What if (like in my case) you only want a specific control to “activate” these validators (ie. your “submit” button). Well, here’s the solution for the problem.

For each validator that you create, you must give it a ValidationGroup that it belongs to. Here’s an example of that:

<asp:TextBox runat="server" ID="TextBox1" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="TextBox1" ErrorMessage="This field is required!" SetFocusOnError="true" ValidationGroup="MyRequiredFields" />

Once we’ve added the ValidationGroup to the validator, we must add the same ValidationGroup to the control that we wish to submit the form.

<asp:LinkButton runat="server" ID="LinkButtonSave" Text="Save" ValidationGroup="MyRequiredFields" />
<asp:LinkButton runat="server" ID="LinkButtonCancel" Text="Cancel" OnClick="CancelAsset" />

Now we can attach any method to the “cancel” button or any other control and it won’t interfere with the validation of our form.

Cheers!

~ by paradoxperfect on November 13, 2007.

Leave a comment