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 RegularExpressionValidator
control for each
text box that must have data matching a specific pattern.
Set the ValidationExpression
attribute of the
RegularExpressionValidator
to the regular
expression needed to match the required pattern.
Add Save and Cancel (or equivalently named) buttons.
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 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.
One of the more common uses of pattern validation is for checking the
form of an email address that has been entered to make sure that it
matches the user@domain pattern. A
RegularExpressionValidator
control is added for
the Email Address text box in the example. The control is placed to
the right of the Email Address text box, to cause the error message
to be displayed beside the text box when an invalid email address is
entered.
The ControlToValidate
attribute of the validation
control must be set to the ID of the control to validate, in our case
txtEmailAddress
:
<asp:RegularExpressionValidator id="revEmailAddress"
Runat="server"
ControlToValidate="txtEmailAddress"
CssClass="AlertText"
Display="Dynamic"
EnableClientScript="True"
ValidationExpression="w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*">
img src="images/arrow_alert.gif">
Invalid Email Address
</asp:RegularExpressionValidator>
The ValidationExpression
attribute is set to the
regular expression that will perform the pattern matching on the data
entered into the text box. Any valid regular expression can be used.
The expression we use in our example is the standard prebuilt
expression for an Internet email address chosen from a pick list in
the Regular Expression Dialog box of Visual Studio .NET, which is
available when setting the ValidateExpression
attribute. The Help that is accessible from this same dialog box
provides a complete explanation of the syntax and can also be used
when writing your own custom regular expressions. Many books are also
available that describe all the nuances of regular expressions,
including Mastering Regular Expressions, so we
won’t go into them here.
<asp:RegularExpressionValidator id="revEmailAddress"
Runat="server"
ControlToValidate="txtEmailAddress"
CssClass="AlertText"
Display="Dynamic"
EnableClientScript="True"
ValidationExpression="w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*">
<img src="images/arrow_alert.gif">
Invalid Email Address
</asp:RegularExpressionValidator>
The error message that is to be output when validation fails is placed between the open and close tags. It can include HTML, as shown here:
<asp:RegularExpressionValidator id="revEmailAddress" Runat="server" ControlToValidate="txtEmailAddress" CssClass="AlertText" Display="Dynamic" EnableClientScript="True" ValidationExpression="w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*"><img src="images/arrow_alert.gif">
Invalid Email Address
</asp:RegularExpressionValidator>
If the email address in this example were required to process the
form, a RequiredFieldValidator
would need to be
added along with the RegularExpressionValidator
.
In all other respects, the .aspx
and code-behind
files are identical to Recipe 2.1.
See that recipe’s discussion for comments about the
Display
, EnableClientScript
,
and CausesValidation
attributes in particular.
You’ll also find explanations of the Save and Cancel
buttons and various other aspects of the code.
Recipe 2.1; Mastering
Regular Expressions, by Jeffrey E. F. Friedl
(O’Reilly); the Help that’s
available from the Regular Expression Dialog box when setting the
ValidateExpression
attribute in Visual Studio .NET
Example 2-6. Form with pattern validation (.aspx)
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH02RegularExpressionValidationVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02RegularExpressionValidationVB" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Regular Expression Validator</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmValidation" method="post" runat="server"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Regular Expression Validation (VB) </td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center"> <table border="0"> <tr> <td class="LabelText">First Name: </td> <td> <asp:TextBox id="txtFirstName" Runat="server" Columns="30" CssClass="LabelText" /> </td> </tr> <tr> <td class="LabelText">Last Name: </td> <td> <asp:TextBox id="txtLastName" Runat="server" Columns="30" CssClass="LabelText" /> </td> </tr> <tr> <td class="LabelText">Age: </td> <td> <asp:TextBox id="txtAge" Runat="server" Columns="30" CssClass="LabelText" /> </td> </tr> <tr> <td class="LabelText">Country: </td> <td> <asp:DropDownList id="ddCountry" Runat="server" > <asp:ListItem Selected="True" Value="0">----- Select Country -----</asp:ListItem> <asp:ListItem Value="1">Canada</asp:ListItem> <asp:ListItem Value="2">United States</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td class="LabelText">Email Address: </td> <td> <asp:TextBox id="txtEmailAddress" Runat="server" Columns="30" CssClass="LabelText" /> <asp:requiredfieldvalidator id="rfvEmailAddress" runat="server" controltovalidate="txtEmailAddress" cssclass="AlertText" display="Dynamic" enableclientscript="True"> <img src="images/arrow_alert.gif"> Email Address Is Required </asp:requiredfieldvalidator><asp:RegularExpressionValidator id="revEmailAddress"
Runat="server"
ControlToValidate="txtEmailAddress"
CssClass="AlertText"
Display="Dynamic"
EnableClientScript="True"
ValidationExpression="w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*">
<img src="images/arrow_alert.gif">
Invalid Email Address
</asp:RegularExpressionValidator>
</td> </tr> <tr> <td class="LabelText">Password: </td> <td> <asp:TextBox id="txtPassword1" Runat="server" TextMode="Password" Columns="30" CssClass="LabelText" /> </td> </tr> <tr> <td class="LabelText">Re-enter Password: </td> <td> <asp:TextBox id="txtPassword2" Runat="server" TextMode="Password" Columns="30" CssClass="LabelText" /> </td> </tr> <tr> <td colspan="2"> <br> <table align="center" width="50%"> <tr> <td align="center"> <asp:ImageButton id="btnSave" Runat="server" CausesValidation="True" ImageUrl="images/buttons/button_save.gif" /> </td> <td align="center"> <asp:ImageButton id="btnCancel" Runat="server" CausesValidation="False" ImageUrl="images/buttons/button_cancel.gif" /> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </form> </body> </html>