Recipe 3.5. 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 validation is for checking the form of an email address entered to ensure 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 and causes the error message to be displayed beside the text box when an invalid email address is entered.

Figure 3-7. Form with pattern validation outputnormal


Figure 3-8. Form with pattern validationwith error message


The ControlToValidate attribute of the validation control must be set to the ID of the control to validate, in our case, txtEmailAddress:

 <asp:RegularExpressionValidator   Runat="server"  ControlToValidate="txtEmailAddress"  Css  Display="Dynamic"  EnableClientScript="True"  ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    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 Editor of Visual Studio 2005, which is available when setting the ValidateExpression attribute (see Figure 3-9). The Help accessible from this same dialog box provides a complete explanation of the syntax and can be used when writing your own custom regular expressions. Many books describe all the nuances of regular expressions, including Mastering Regular Expressions (O'Reilly), so we won't go into them here.

 <asp:RegularExpressionValidator   Runat="server"  ControlToValidate="txtEmailAddress"  Css  Display="Dynamic"  EnableClientScript="True"  ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    Invalid Email Address </asp:RegularExpressionValidator> 

Figure 3-9. Regular Expression Editor


The error message to be output when validation fails is placed between the open and close tags. It can include HTML, as shown here:

 <asp:RegularExpressionValidator   Runat="server"  ControlToValidate="txtEmailAddress"  Css  Display="Dynamic"  EnableClientScript="True"  ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">    <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>    Invalid Email Address </asp:RegularExpressionValidator> 

If the email address in this example was 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 those in Recipe 3.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.

See Also

Recipe 3.1; search Regular Expression Examples in the MSDN Library; Mastering Regular Expressions, by Jeffrey E. F. Friedl (O'Reilly); the Help available from the Regular Expression dialog box when setting the ValidateExpression attribute in Visual Studio 2005.

Example 3-6. Form with pattern validation (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"    AutoEventWireup="false"    CodeFile="CH03RegularExpressionValidationVB.aspx.vb"    Inherits="ASPNetCookbook.VBExamples.CH03RegularExpressionValidationVB"    title="Regular Expression Validator" %> <asp:Content  Runat="server" ContentPlaceHolder>    <div align="center" >   Regular Expression Validation (VB)    </div>    <table align="center" ></tr>   <td >First Name: </td>   <td>  <asp:TextBox  Runat="server" Columns="30" Css />  </td>  </tr>  </tr>  <td >Last Name: </td>  <td> <asp:TextBox  Runat="server" Columns="30" Css />  </td>  </tr>  </tr>  <td >Age: </td>  <td>         <asp:TextBox  Runat="server" Columns="30" Css /> </td>  </tr>  </tr>  <td >Country: </td>  <td> <asp:DropDownList  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 >Email Address: </td> <td> <asp:TextBox  Runat="server" Columns="30" Css /> <asp:requiredfieldvalidator     runat="server"    controltovalidate="txtEmailAddress"    css    display="Dynamic"    enableclientscript="True">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>  Email Address Is Required </asp:requiredfieldvalidator> <asp:RegularExpressionValidator       Runat="server"    ControlToValidate="txtEmailAddress"    Css    Display="Dynamic"    EnableClientScript="True"   ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">  <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/>  Invalid Email Address </asp:RegularExpressionValidator>    </td> </tr> </tr> <td >Password: </td> <td> <asp:TextBox  Runat="server" TextMode="Password" Columns="30" Css />    </td> </tr> </tr> <td >Re-enter Password: </td> <td> <asp:TextBox  Runat="server" TextMode="Password" Columns="30" Css /> </td> </tr> </tr>   <td colspan="2">   <br/>   <table align="center" width="50%"></tr>  <td align="center"> <input  runat="server" type="button" value="Save" causesvalidation="true" onserverclick="btnSave_ServerClick"/> </td> <td align="center"> <input  runat="server" type="button" value="Cancel" causesvalidation="false" onserverclick="btnCancel_ServerClick" />   </td>   </tr>    </table> </td>  </tr>    </table> </asp:Content> 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net