O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.3. Requiring That Two Data Input Fields Match

Problem

You need to make sure the data a user enters in two fields on an input form is the same, such as when performing password or email verification.

Solution

Add RequiredFieldValidator controls to the .aspx file for both TextBox controls to prevent a user from skipping one of the fields. Next, add a CompareValidator control to one of the TextBox controls. Finally, verify that validation was successful from within the event handler of the control that completes the user’s entry for the page.

In the .aspx file:

  1. Add a RequiredFieldValidator control for each of the two text boxes in which the user must enter matching data.

  2. Add a CompareValidator control to the control that must have its input match the other control (usually the second one).

  3. Add Save and Cancel (or equivalently named) buttons.

  4. Set the Save button’s CausesValidation attribute to True to have validation performed when the button is clicked (set it to False for the Cancel button).

In the code-behind class for the page, use the .NET language of your choice to add code to the event handler for the Save 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-5 shows a typical form with normal output prior to data entry. Figure 3-6 shows the error message that appears on the form when the user enters passwords that do not match. Example 3-5 shows the .aspx file for the solution we have implemented ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required