ASP.NET Tutorial/Validation/Regular Expression
Содержание
[убрать]- 1 Commonly Used Regular Expressions
- 2 Metacharacters for Matching Single Characters
- 3 Metacharacters for Matching Types of Characters
- 4 Quantifiers
- 5 quantifiers used to create patterns that match a variable number of characters at a certain position in the string
- 6 Regular Expression based validation (C#)
- 7 RegularExpressionValidator compares value against a regular expression
- 8 The predefined character classes
- 9 Use asp:RegularExpressionValidator to check the email address
- 10 Use asp:RegularExpressionValidator to check the zip code
- 11 Use Regular expression to validate a Phone number
Commonly Used Regular Expressions
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}
Metacharacters for Matching Single Characters
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.
Metacharacters for Matching Types of Characters
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.
Quantifiers
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
quantifiers used to create patterns that match a variable number of characters at a certain position in the string
?: 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
Regular Expression based validation (C#)
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">
<div>
<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>
<div>
<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>
</div>
</div>
</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;
}
}
RegularExpressionValidator compares value against a regular expression
<%@ 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">
<div>
<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" />
<br /><br />
<asp:Button
id="btnSubmit"
Text="Submit"
Runat="server" />
</div>
</form>
</body>
</html>
The predefined character classes
. : 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
Use asp:RegularExpressionValidator to check the email address
<html><body>
<form runat="server">
<asp:Label id="lblMessage" runat="server" /><br>
<asp:Panel id="Panel1" runat="server">
<table>
<tr>
<td valign="top">Email (.ru"s only):</td>
<td valign="top">
<asp:TextBox id="tbEmail"
runat="server" /><br>
<asp:RegularExpressionValidator runat="server"
ControlToValidate="tbEmail"
ValidationExpression="\w+\@\w+\.ru"
ErrorMessage="That is not a valid email" />
</td>
</tr>
<tr>
<td colspan="2" valign="top" align="right">
<asp:Button id="Submit" runat="server"
text="Add" />
</td>
</tr>
</table>
</asp:Panel>
</form>
</body></html>
Use asp:RegularExpressionValidator to check the zip code
<html><body>
<form runat="server">
<asp:Label id="lblMessage" runat="server" /><br>
<asp:Panel id="Panel1" runat="server">
<table>
<tr>
<td valign="top">City, State, ZIP (5-digit):</td>
<td valign="top">
<asp:TextBox id="tbCity"
runat="server" />,
<asp:TextBox id="tbState" runat="server"
size=2 />
<asp:TextBox id="tbZIP" runat="server"
size=5 /><br>
<asp:RegularExpressionValidator runat="server"
ControlToValidate="tbZIP"
ValidationExpression="[0-9]{5}"
ErrorMessage="That is not a valid ZIP" /><br>
<asp:RangeValidator runat="server"
ControlToValidate="tbZIP"
MinimumValue="00000" MaximumValue="22222"
Type="String"
ErrorMessage="You don"t live in the correct region" />
</td>
</tr>
<tr>
<td colspan="2" valign="top" align="right">
<asp:Button id="Submit" runat="server"
text="Add" />
</td>
</tr>
</table>
</asp:Panel>
</form>
</body></html>
Use Regular expression to validate a Phone number
<html><body>
<form runat="server">
<asp:Label id="lblMessage" runat="server" /><br>
<asp:Panel id="Panel1" runat="server">
<table>
<tr>
<td valign="top">Phone (<i>xxx-xxxx</i>):</td>
<td valign="top">
<asp:TextBox id="tbPhone" runat="server"
size=11 /><br>
<asp:RegularExpressionValidator runat="server"
ControlToValidate="tbPhone"
ValidationExpression="[0-9]{3}-[0-9]{4}"
ErrorMessage="That is not a valid phone" />
</td>
</tr>
<tr>
<td colspan="2" valign="top" align="right">
<asp:Button id="Submit" runat="server"
text="Add" />
</td>
</tr>
</table>
</asp:Panel>
</form>
</body></html>