2.4. Requiring that Data Matches 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:
Add a
RegularExpressionValidatorcontrol for each text box that must have data matching a specific pattern.Set the
ValidationExpressionattribute of theRegularExpressionValidatorto the regular expression needed to match the required pattern.Add Save and Cancel (or equivalently named) buttons.
Set the Save button’s
CausesValidationattribute toTrueto have validation performed when the button is clicked (set it toFalsefor 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 2.1 for details.)
Figure 2-7 shows a typical form with normal,
error-free output. Figure 2-8 shows the error
message that appears on the form when an invalid email address is
entered. Example 2-6 shows the
.aspx file for our application that implements
the recipe. See Example 2-2 and Example 2-3 (Recipe 2.1) for the companion code-behind
files.
Figure 2-7. Form with pattern ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access