3.4. Requiring Data to Match a Predefined Pattern

Problem

You need to make sure the data a user enters matches a specific pattern, such as an email address.

Solution

Add a RegularExpressionValidator control to the .aspx file, set the regular expression to perform the pattern matching, and 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 RegularExpressionValidator control for each text box that must have data matching a specific pattern.

  2. Set the ValidationExpression attribute of the RegularExpressionValidator to the regular expression needed to match the required pattern.

  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-7 shows a typical form with normal, error-free output. Figure 3-8 shows the error message that appears on the form when an invalid email address is entered. Example 3-6 shows the .aspx file for our application that implements the recipe. (See Examples 3-2 and 3-3 [Recipe 3.1] for the companion code-behind files.)

Discussion

One of the more common uses of pattern ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.