3.8. Performing Validation Programmatically to Execute Your Own Application-Specific Logic

Problem

You have two logical sections on a form with controls that require different validation as a function of the button the user clicks. You want to have programmatic control over the validation performed because your application needs to carry out its own application-specific logic, such as when you want to check a new user’s registration against a database.

Solution

For each group of controls and their associated form-submit button, set the ValidationGroup attribute to a unique group name. This will cause only the controls with a group name matching the group name of the button to be validated when the button is clicked.

In the .aspx file:

  1. Set the ValidationGroup attribute of a form-submit button to a unique group name.

  2. Set the ValidationGroup attribute of each of the controls to be validated when the button is clicked to the same group name as the form-submit button.

  3. Set the form-submit button’s CausesValidation attribute to False to disable both the client-side and server-side validation performed by ASP.NET when the button is clicked.

  4. Repeat steps 1–3 for each form-submit button and its associated controls.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Add an event handler for each form-submit button.

  2. Add code to the event handler to get the collection of validators associated with the button.

  3. Iterate through the collection performing the required validation. ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.