ASP.NET Regular Expression Validator Control
Regular expressions are a good way to validate text fields such as names, addresses, phone numbers, and other user information. You can use them to constrain input, apply formatting rules, and check lengths. To validate input captured with server controls, you can use the RegularExpressionValidator control. To validate other forms of input, such as query strings, cookies, and HTML control input, you can use the System.Text.RegularExpressions.Regex class.
Using Regular Expression Validator Control
If you capture input by using server controls, you can use the RegularExpressionValidator control to validate that input. You can use regular expressions to restrict the range of valid characters, to strip unwanted characters, and to perform length and format checks. You can constrain the input format by defining patterns that the input must match.
To validate a servers control’s input by using a RegularExpressionValidator control
- Add a RegularExpressionValidator control to your page.
- Set the ControlToValidate property to indicate which control to validate.
- Set the ValidationExpression property to an appropriate regular expression.
- Set the ErrorMessage property to define the message to display if the validation fails.
The following example shows a RegularExpressionValidator control used to validate a name field.
<%@ language="C#" %>
<form id="form1" runat="server">
<asp:TextBox ID="txtUserName" runat="server"/>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
<asp:RegularExpressionValidator ID="RegExpUserName" runat="server"
ErrorMessage="This expression does not validate."
ControlToValidate="txtUserName"
ValidationExpression="^[a-zA-Z'.s]{1,40}$" />
</form>
The regular expression used in the preceding code example constrains an input name field to alphabetic characters (lowercase and uppercase), space characters, the single quotation mark (or apostrophe) for names such as O’Dell, and the period or dot character. In addition, the field length is constrained to 40 characters.
Using ^ and $
Enclosing the expression in the caret (^) and dollar sign ($)markers ensures that the expression consists of the desired content and nothing else. A ^ matches the position at the beginning of the input string and a $ matches the position at the end of the input string. If you omit these markers, an attacker could affix malicious input to the beginning or end of valid content and bypass your filter.
