asp.net.ph

Skip Navigation Links

Validating Against Patterns

ASP.NET Web Forms   Web Forms Server Controls   Web Forms Validation


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.

To validate against a regular expression

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

Property Setting
ControlToValidate The ID of the input control that the validation control will evaluate.
Display The display behavior for the specified validation control.
ErrorMessage The error message to display in the ValidationSummary control if validation fails.
Text The error message to display in the validation control when validation fails.
  1. Set the pattern to compare to by setting the ValidationExpression property to a regular expression.

    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.

  2. In your Web Forms code, check for validity. For details, see Testing Validity Programmatically.

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.

<asp:textbox id="txtZip" runat="server" />

<asp:regularexpressionvalidator id="zipValidator" runat="server" 
   controltovalidate="txtZip"
   errormessage="Enter a valid US ZIP code."
   validationexpression="\d{5} ( -\d{4} ) ?" />
See Also

RegularExpressionValidator Control   RegularExpressionValidator Class   Regular Expressions Language Elements   Data Entry Validation ( Client-Side )



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note