3.6. Requiring Data to Match a Database Entry

Problem

You need to make sure the data a user enters matches an entry in a database.

Solution

Add a CustomValidator to the .aspx file. Then add an event handler to the codebehind for the CustomValidator control’s ServerValidate event, its purpose beingto validate the user entries against the database.

In the .aspx file:

  1. Add a CustomValidator control that validates the entries against the database during server-side validation.

  2. Add a Login (or equivalently named) button.

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

  1. Add an event handler for the CustomValidator control’s ServerValidate event, its purpose beingto provide the server-side validation of the user’s entries against the database.

  2. Add code to the event handler for the Login button’s click event to check the Page.IsValid property and verify that all validation was successful (see Recipe 3.1 for details).

Figure 3-12 shows a typical form with normal output prior to data entry. Figure 3-13 shows the form with a validation error message. Examples 3-10, 3-11 through 3-12 show the .aspx and code-behind files for our application that implements the solution.

Discussion

One of the most common examples of this recipe’s handiness is when implementing a classic login page. The approach we favor in this scenario uses a CustomValidator to perform the user authentication and a ValidationSummary to display error information.

Figure 3-12. Form with database validation output—normal ...

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.