Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Using the RegularExpressionValidator Control

The RegularExpressionValidator control enables you to compare the value of a form field against a regular expression. You can use a regular expression to represent string patterns such as email addresses, Social Security numbers, phone numbers, dates, currency amounts, and product codes.

For example, the page in Listing 3.13 enables you to validate an email address (see Figure 3.11).


Figure 3.11 Validating an email address.

Example 3.13. ShowRegularExpressionValidator.aspx

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show RegularExpressionValidator</title>
    <form id="form1" runat="server">

        Text="Email Address:"
        Runat="server" />
        Runat="server" />
        Text="(Invalid email)"
        Runat="server" />

    <br /><br />

        Runat="server" />


The regular expression is assigned to the RegularExpressionValidator control's ValidationExpression property. It looks like this:


Regular expressions are not fun to read. This pattern matches a simple email address. The \w expression represents any non-whitespace character. Therefore, roughly, this regular expression matches an email address that contains non-whitespace characters, followed by an @ sign, followed by non-whitespace characters, followed by a period, followed by more non-whitespace characters.

Just like the other validation controls, the RegularExpressionValidator doesn't validate a form field unless the form field contains a value. To make a form field required, you must associate a RequiredFieldValidator control with the form field.

  • + Share This
  • 🔖 Save To Your Account