Using the ASP.NET RegularExpressionValidator Control

The RegularExpressionValidator control enables you to compare the value of a form field against a string pattern represented by a regular expression. You can use the RegularExpressionValidator control to verify social security numbers, email addresses, product codes, or any string that follows a definite pattern.

The regular expression language enables you to specify string patterns. Here are some samples of common regular expressions:

Email Address:

Internet Address: http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

Social Security Number: \d{3}-\d{2}-\d{4}

When using the RegularExpressionValidator, there are three important properties which you must set.

ControlToValidate – The id of the form control being validated.

Text – The error message displayed when validation fails.

ValidationExpression – The regular expression pattern used for validation.

Matching a String Pattern

The following page contains a RegularExpressionValidator control which is used for validating an Internet Address. If you don’t enter a string that looks like a valid URL, the RegularExpressionValidator control displays an error message.