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.
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.
To validate against a regular expression
Add acontrol to the page and set the following properties:
The ID of the control you are validating.
Properties that specify the text and location of the error or errors that will display if the validation fails. For details, see.
Set the pattern to compare to by setting theproperty to a regular expression.
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.
Add a test in your ASP.NET Web page code to check for validity. For details, see.
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.