How to: Validate 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 noteSecurity Note

By default, ASP.NET Web pages automatically validate that malicious users are not attempting to send script or HTML elements to your application. For more information, see Script Exploits Overview.

To validate against a regular expression

  1. Add a RegularExpressionValidator control to the page and set the following properties:

    Property Description

    ControlToValidate

    The ID of the control you are validating.

    ErrorMessage, Text, Display

    Properties that specify the text and location of the error or errors that will display if the validation fails. For details, see How to: Control 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.

    NoteNote

    If you are using a visual designer such as Visual Studio .NET 2005, you can select from predefined patterns defined in the RegularExpressionValidator control.

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

    NoteNote

    In client-side validation, regular expressions are evaluated using ECMAScript (JavaScript). This differs in minor ways from server-side regular-expression checking.

  3. Add a test in your ASP.NET Web page code to check for validity. For details, see How to: Test Validity Programmatically for ASP.NET Server Controls.

    The following code example shows how you can use a RegularExpressionValidator control to check whether users have entered 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>
         <asp:RegularExpressionValidator 
           id="txtZIP_validation" runat="SERVER" 
           ControlToValidate="txtZIP" 
           ErrorMessage="Enter a valid US ZIP code."
           ValidationExpression="\d{5}(-\d{4})?">
         </asp:RegularExpressionValidator>
    
    ZIP: <asp:TextBox id="txtZIP" runat="SERVER"></asp:TextBox>
         <asp:RegularExpressionValidator 
           id="txtZIP_validation" runat="SERVER" 
           ControlToValidate="txtZIP" 
           ErrorMessage="Enter a valid US ZIP code."
           ValidationExpression="\d{5}(-\d{4})?">
         </asp:RegularExpressionValidator>
    

See Also

Concepts

Types of Validation for ASP.NET Server Controls

Other Resources

Validation ASP.NET Controls