ASP.NET Tutorial/Validation/Regular Expression

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Commonly Used Regular Expressions

   <source lang="csharp">

Content Regular Expression E-mail address[*] \S+@\S+\.\S+ Password \w+ Specific-length password \w{4,10} Advanced password [a�CzA�CZ]\w{3,9} Another advanced password [a�CzA�CZ]\w*\d+\w* Limited-length field \S{4,10} Social Security number \d{3}-\d{2}-\d{4}</source>


Metacharacters for Matching Single Characters

   <source lang="csharp">

Character Escapes Description Ordinary characters Characters other than .$^{[(|)*+?\ match themselves. \b Matches a backspace. \t Matches a tab. \r Matches a carriage return. \v Matches a vertical tab. \f Matches a form feed. \n Matches a newline. \ If followed by a special character (one of .$^{[(|)*+?\),

                          this character escape matches that character literal. 
                          For example, \+ matches the + character.</source>
   
  

Metacharacters for Matching Types of Characters

   <source lang="csharp">

Character Class Description . Matches any character except \n. [aeiou] Matches any single character specified in the set. [^aeiou] Matches any character not specified in the set. [3-7a-dA-D] Matches any character specified in the specified ranges (in the example the ranges are 3�C7, a�Cd, A�CD). \w Matches any word character; that is, any alphanumeric character or the underscore (_). \W Matches any nonword character. \s Matches any whitespace character (space, tab, form-feed, newline, carriage return, or vertical feed). \S Matches any nonwhitespace character. \d Matches any decimal character. \D Matches any nondecimal character.</source>


Quantifiers

   <source lang="csharp">

Quantifier Description

  • Zero or more matches

+ One or more matches ? Zero or one matches {N} N matches {N,} N or more matches {N,M} Between N and M matches</source>


quantifiers used to create patterns that match a variable number of characters at a certain position in the string

   <source lang="csharp">

?: Zero or one times

  • Zero or more times

+: One or more times {n}: Exactly n times {n,}: At least n times {n,m}: At least n times but no more than m times</source>


Regular Expression based validation (C#)

   <source lang="csharp">

File: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="RegularExpressionTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Regular Expression Test</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:textbox id="txtExpression" 
                    runat="server" 
                    Width="192px"></asp:textbox>
       <asp:button id="cmdSetExpression" 
                   runat="server" 
                   Width="138px" 
                   Text="Set This Expression" 
                   CausesValidation="False" 
                   OnClick="cmdSetExpression_Click">
       </asp:button>
       <asp:label id="lblExpression" 
                  runat="server" 
                  Height="21px" 
                  Width="512px" >Current Expression: (none)</asp:label>
       <asp:label id="Label1" 
                  runat="server" >New Expression:</asp:label>
   
     <asp:validationsummary id="ValidationSummary1" runat="server" ></asp:validationsummary>
     <asp:regularexpressionvalidator id="TestValidator" 
                                     runat="server" 
                                     EnableClientScript="False" 
                                     ErrorMessage="Failed Validation" 
                                     ControlToValidate="txtValidate"></asp:regularexpressionvalidator>
     <asp:textbox id="txtValidate" runat="server" Width="192px"></asp:textbox>
     <asp:button id="cmdValidate" runat="server"  Width="139px" Text="Validate"></asp:button>
     <asp:label id="Label2" runat="server" Height="16px" Width="184px" >Test Current Expression:</asp:label>
   </form>

</body> </html>

File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class RegularExpressionTest : System.Web.UI.Page {

 protected void cmdSetExpression_Click(object sender, EventArgs e)
 {
   TestValidator.ValidationExpression = txtExpression.Text;
   lblExpression.Text = "Current Expression: ";
   lblExpression.Text += txtExpression.Text;
 }

}</source>


RegularExpressionValidator compares value against a regular expression

   <source lang="csharp">

<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">

   <title>Show RegularExpressionValidator</title>

</head> <body>

   <form id="form1" runat="server">
   <asp:Label
       id="lblEmail"
       Text="Email Address:"
       AssociatedControlID="txtEmail"
       Runat="server" />
   <asp:TextBox
       id="txtEmail"
       Runat="server" />
   <asp:RegularExpressionValidator
       id="regEmail"
       ControlToValidate="txtEmail"
       Text="(Invalid email)"
       ValidationExpression="\w+([-+."]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
       Runat="server" />
   

<asp:Button id="btnSubmit" Text="Submit" Runat="server" />
   </form>

</body> </html></source>


The predefined character classes

   <source lang="csharp">

. : Any character \d: Any digit \D: Any non-digit \s: Any white-space character (such as spaces, tabs, newlines, returns, and backspaces) \S: Any character other than a white space character \w: Any word character \W: Any character other than a word character</source>


Use asp:RegularExpressionValidator to check the email address

   <source lang="csharp">

<html><body>

  <form runat="server">
     <asp:Label id="lblMessage" runat="server" />
<asp:Panel id="Panel1" runat="server">
Email (.ru"s only):
              <asp:TextBox id="tbEmail" 
                 runat="server" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="tbEmail" ValidationExpression="\w+\@\w+\.ru" ErrorMessage="That is not a valid email" />
              <asp:Button id="Submit" runat="server" 
                 text="Add" />
     </asp:Panel>
  </form>

</body></html></source>


Use asp:RegularExpressionValidator to check the zip code

   <source lang="csharp">

<html><body>

  <form runat="server">
     <asp:Label id="lblMessage" runat="server" />
<asp:Panel id="Panel1" runat="server">
City, State, ZIP (5-digit):
              <asp:TextBox id="tbCity" 
                 runat="server" />,
              <asp:TextBox id="tbState" runat="server"
                 size=2 /> 
              <asp:TextBox id="tbZIP" runat="server"
                 size=5 />
<asp:RegularExpressionValidator runat="server" ControlToValidate="tbZIP" ValidationExpression="[0-9]{5}" ErrorMessage="That is not a valid ZIP" />
<asp:RangeValidator runat="server" ControlToValidate="tbZIP" MinimumValue="00000" MaximumValue="22222" Type="String" ErrorMessage="You don"t live in the correct region" />
              <asp:Button id="Submit" runat="server" 
                 text="Add" />
     </asp:Panel>
  </form>

</body></html></source>


Use Regular expression to validate a Phone number

   <source lang="csharp">

<html><body>

  <form runat="server">
     <asp:Label id="lblMessage" runat="server" />
<asp:Panel id="Panel1" runat="server">
Phone (xxx-xxxx):
              <asp:TextBox id="tbPhone" runat="server"
                 size=11 />
<asp:RegularExpressionValidator runat="server" ControlToValidate="tbPhone" ValidationExpression="[0-9]{3}-[0-9]{4}" ErrorMessage="That is not a valid phone" />
              <asp:Button id="Submit" runat="server" 
                 text="Add" />
     </asp:Panel>
  </form>

</body></html></source>