2.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 code-behind for the CustomValidator control’s ServerValidate event, whose purpose is to 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 whose purpose is to 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 2.1 for details).

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

Form with database validation output—normal

Figure 2-11. Form with database validation output—normal

Form with database validation output—with error message

Figure 2-12. Form with database validation output—with ...

Get ASP.NET Cookbook 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.