This documentation is archived and is not being maintained.

Validating Against Patterns for ASP.NET Server Controls

You can check that a user's entry matches a predefined pattern, such as a phone number, postal code, e-mail address, and so on. To do so, you use a regular expression. For more information on regular expressions, see .NET Framework Regular Expressions.

Security Note   By default, the Web Forms page automatically validates that malicious users are not attempting to send script or HTML elements to your application. As long as this validation is enabled, you do not need to explicitly check for script or HTML elements in user input. For more information, see Scripting Exploits.

To validate against a regular expression

  1. Add a RegularExpressionValidator control to the page and set the following properties:
    ControlToValidateThe ID of the control you are validating.
    ErrorMessage, Text, DisplayProperties that specify the text and location of the error or errors that will display if the validation fails. For details, see Controlling Validation Error Message Display for ASP.NET Server Controls.
  2. Set the pattern to compare to by setting the ValidationExpression property to a regular expression. To select from predefined patterns, click the ValidationExpression property in the Properties window and then click the ellipsis button (6xh899wy.vbellipsesbutton(en-us,VS.71).gif).

    If you want to allow multiple valid patterns, use the bar character (|) to separate expressions.

    Note   In client-side validation, regular expressions are evaluated using ECMAScript (JScript). This differs in minor ways from server-side regular-expression checking.
  3. Add a test in your Web Forms code to check for validity. For details, see Testing Validity Programmatically for ASP.NET Server Controls.

    The following example shows how you can use a RegularExpressionValidator control to check whether users enter a valid United States ZIP code. The validator checks for two patterns: five digits, and five digits plus a hyphen plus four more digits.

    ZIP: <asp:TextBox id=txtZIP runat="SERVER"></asp:TextBox>
         id=txtZIP_validation runat="SERVER" 
         ErrorMessage="Enter a valid US ZIP code."

See Also

Introduction to Validating User Input in Web Forms | Controlling Validation Error Message Display for ASP.NET Server Controls