ASP.Net/Validation by Control/Regular Expression Validator
Содержание
A valid 5 digit zip code
<source lang="csharp">
<%@ Page Language="C#" %> <!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>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:TextBox ID="txtValue" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Submit" /> <asp:RegularExpressionValidator ControlToValidate="txtValue" ErrorMessage="RegularExpressionValidator" SetFocusOnError=true ID="RegularExpressionValidator1" runat="server" ValidationExpression="\d{5}(-\d{4})?">Please enter a valid 5 digit zip code</asp:RegularExpressionValidator>
</form>
</body> </html>
</source>
Regular expression validator: ^\d{5}$|^\d{5}-\d{4}$ (VB.net)
<source lang="csharp">
<%@ Page Language="vb" %> <html> <head>
<title>Validation Control Example</title> <script language="javascript"> </script> <script runat="server"> Sub Page_Load() vsSummary.DisplayMode = ValidationSummaryDisplayMode.List End Sub Sub ServerValidation (source As object, args As ServerValidateEventArgs) Dim RegExVal As New System.Text.RegularExpressions.Regex("^\d{4}$") If RegExVal.IsMatch(args.Value) Then args.IsValid = True Else args.IsValid = False End If End Sub </script>
</head> <body>
Validation Control Example
<form runat="server"> <asp:table id="MyTable" border="1" cellpadding="5" cellspacing="0" runat="server"> <asp:tablerow runat="server"> <asp:tablecell runat="server"> RegularExpressionValidator Control:
Enter a valid 5 or 9-digit zip code </asp:tablecell> <asp:tablecell runat="server"> <asp:textbox id="zipcode" runat="server"/>
<asp:regularexpressionvalidator id="reZipCode" controltovalidate="zipcode" validationexpression="^\d{5}$|^\d{5}-\d{4}$" errormessage="Not a valid Zip code!" display="static" runat="server"/> </asp:tablecell> </asp:tablerow> <asp:tablerow runat="server"> <asp:tablecell runat="server"> RequiredFieldValidator Control:
Enter a login name </asp:tablecell> <asp:tablecell runat="server"> <asp:textbox id="login" runat="server"/>
<asp:requiredfieldvalidator id="rfvLogin" controltovalidate="login" display="static" errormessage="Login cannot be blank!" runat="server"/> </asp:tablecell> </asp:tablerow>
<asp:tablerow runat="server"> <asp:tablecell runat="server"> ValidationSummary Control: </asp:tablecell> <asp:tablecell runat="server"> <asp:validationsummary id="vsSummary" displaymode="bulletlist" headertext="Page has the following errors: " showsummary="true" showmessagebox="false" runat="server"/> </asp:tablecell> </asp:tablerow> <asp:tablerow runat="server"> <asp:tablecell colspan="2" runat="server"> <asp:button text="submit" runat="server"/> </asp:tablecell> </asp:tablerow> </asp:table> <asp:label id="MyLabel" runat="server"/> </form>
</body> </html>
</source>
Try validation based on Regular Expression in C#
<source lang="csharp">
<%@ Page language="c#" src="RegularExpressionTest.aspx.cs" AutoEventWireup="false" Inherits="RegularExpressionTest" %> <HTML>
<body> <form id="Form1" method="post" runat="server"> <asp:textbox id="txtExpression" style="Z-INDEX: 104; LEFT: 224px; POSITION: absolute; TOP: 48px" runat="server" Height="24px" Width="192px"></asp:textbox><asp:button id="cmdSetExpression" style="Z-INDEX: 103; LEFT: 424px; POSITION: absolute; TOP: 48px" runat="server" Height="25px" Width="138px" Text="Set This Expression" CausesValidation="False"></asp:button><asp:label id="lblExpression" style="Z-INDEX: 105; LEFT: 24px; POSITION: absolute; TOP: 16px" runat="server" Height="21px" Width="512px" Font-Bold="True" Font-Size="X-Small" Font-Names="Verdana">Current Expression: (none)</asp:label><asp:label id="Label1" style="Z-INDEX: 106; LEFT: 88px; POSITION: absolute; TOP: 56px" runat="server" Font-Bold="True" Font-Size="X-Small" Font-Names="Verdana">New Expression:</asp:label>
</form> </body>
</HTML>
<%-- using System; using System.Collections; using System.ruponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;
public class RegularExpressionTest : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox txtExpression; protected System.Web.UI.WebControls.Button cmdSetExpression; protected System.Web.UI.WebControls.Label lblExpression; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.ValidationSummary ValidationSummary1; protected System.Web.UI.WebControls.RegularExpressionValidator TestValidator; protected System.Web.UI.WebControls.TextBox txtValidate; protected System.Web.UI.WebControls.Button cmdValidate; protected System.Web.UI.WebControls.Label Label2; private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdSetExpression.Click += new System.EventHandler(this.cmdSetExpression_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void cmdSetExpression_Click(object sender, System.EventArgs e) { TestValidator.ValidationExpression = txtExpression.Text; lblExpression.Text = "Current Expression: "; lblExpression.Text += txtExpression.Text; } }
--%>
</source>
Using a RegularExpressionValidator Control to Prevent the Entry of a Special Character (VB.net)
<source lang="csharp">
<%@ Page Language=VB Debug=true %>
<HTML>
<HEAD>
<TITLE>Using a RegularExpressionValidator Control to Prevent the Entry of a Special Character</TITLE>
</HEAD>
<form runat="server">
Enter a value that does not include the " character:
<asp:textbox
id="txtValue" runat=server
/> <asp:regularexpressionvalidator
id="regZipCode" controltovalidate="txtValue" validationexpression="[^"]*" display="Dynamic" font-name="Arial" font-size="11" runat=server
>
You must not use the " character.
</asp:regularexpressionvalidator>
<asp:button
id="butOK" text="OK" type="Submit" runat="server"
/> </form> </BODY> </HTML>
</source>
Validate input of US SSN
<source lang="csharp">
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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>Untitled Page</title>
</head> <body>
<form id="form1" runat="server">
<asp:Label ID="Label5" runat="server" Font-Bold="True" Font-Size="Large" Text="ASP.NET Validators"/> <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Required Field:"/> <asp:TextBox ID="txtRequiredField" runat="server">Name</asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtRequiredField" ErrorMessage="No data." InitialValue="Please enter your name"/> <asp:Label ID="Label2" runat="server" Font-Bold="True" Text="Range 0 - 100:"/> <asp:TextBox ID="txtRange" runat="server"/> <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtRange" ErrorMessage="Should be between 0 and 100." MaximumValue="100" MinimumValue="0" Type="Integer"/> <asp:Label ID="Label3" runat="server" Font-Bold="True" Text="Regular Expression:"/> <asp:TextBox ID="txtRegExp" runat="server"></asp:TextBox> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtRegExp" ErrorMessage="Please enter a valid US SSN." ValidationExpression="\d{3}-\d{2}-\d{4}"/> <asp:Label ID="Label4" runat="server" Font-Bold="True" Text="Value < 20"/> <asp:TextBox ID="txtComparison" runat="server"></asp:TextBox> <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtComparison" ErrorMessage="Enter a value less than 20." Operator="LessThan" ValueToCompare="20"/> <asp:Button ID="btnPostback" runat="server" OnClick="btnPostback_Click" Text="Post back" /> <asp:Label ID="lblValidationComplete" runat="server"/>
</form>
</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; 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 _Default : System.Web.UI.Page {
protected void btnPostback_Click(object sender, EventArgs e) { lblValidationComplete.Text = "You passed validation!"; }
}
</source>