Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Validating Expressions: The RegularExpressionValidator Control

You can use RegularExpressionValidator to match the value entered into a form field to a regular expression. You can use this control to check whether a user has entered, for example, a valid e-mail address, telephone number, or username or password. Samples of how to use a regular expression to perform all these validation tasks are provided in the following sections. The properties and methods of this control are listed in Table 3.2.

Table 3.2 RegularExpressionValidator Properties, Methods, and Events

Properties

Description

ControlToValidate

Specifies the id of the control that you want to validate.

Display

Sets how the error message contained in the Text property is displayed. Possible values are Static, Dynamic, and None; the default value is Static.

EnableClientScript

Enables or disables client-side form validation. This property has the value True by default.

Enabled

Enables or disables both server and client-side validation. This property has the value True by default.

ErrorMessage

Specifies the error message that is displayed in the ValidationSummary control. This error message is displayed by the control when the Text property is not set.

IsValid

Has the value True when the validation check succeeds and False otherwise.

Text

Sets the error message displayed by the control.

ValidationExpression

Specifies the regular expression to use when performing validation.

Methods

Description

Validate

Performs validation and updates the IsValid property.

Events

Description

None

 


NOTE

Regular expressions are discussed in detail in Chapter 24, "Working with Collections and Strings."

You assign the regular expression that you want to use when performing validation to the ValidationExpression property. You can perform complex types of validation by using the correct regular expression.

WARNING

Regular expressions work somewhat differently in JavaScript than they do in the .NET framework. So, in certain circumstances, the client-side validation code used for matching regular expressions might return different results than the server-side validation code. Even worse, a valid .NET regular expression might generate a JavaScript error. For example, the syntax for using regular expression options inline—such as the i option—differs between JavaScript and the .NET classes.

You can submit the form in Listing 3.4, for example, only if you enter a product code that starts with the uppercase letter P and contains no more, or no fewer, than four numerals in a row. The RegularExpressionValidator control uses the regular expression P[0-9]{4}.

Listing 3.4 RegularExpressionValidator.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "ThankYou.aspx" )
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionValidator.aspx</title></head>
<body>

<form Runat="Server">

Product Code:
<br>
<asp:TextBox
 id="txtProductCode"
 Runat="Server"/>

<asp:RegularExpressionValidator
 ControlToValidate="txtProductCode"
 Text="Invalid Product Code!"
 ValidationExpression="P[0-9]{4}"
 Runat="Server" />
<p>
<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>
</body>
</html>

If you experiment with the page contained in Listing 3.4, you'll quickly discover that you can submit the form without entering any text into the text box. The RegularExpressionValidator control does not require a value.

The only way to require a value is to combine RegularExpressionValidator with RequiredFieldValidator. Nothing prevents you from associating multiple Validator controls with the same control.

Validating E-Mail Addresses

One of the most common and difficult validation tasks that arise when performing form validation is validating an e-mail address. This task is actually much more difficult than you might assume because the e-mail standard is so complicated.

NOTE

You can find the specification for e-mail addresses in RFC 822, Standard for ARPA Internet Text Messages, at the following location:

ftp://ftp.rfc-editor.org/in-notes/rfc822.txt

Even if a perfect e-mail validation regular expression is beyond your grasp, however, you can still hope to validate simple e-mail addresses. For example, you can use the following regular expression to check that an e-mail address starts with one or more nonwhitespace characters, followed by an @ sign, followed by one or more nonwhitespace characters, followed by a period, followed by one or more nonwhitespace characters:

\S+@\S+\.\S+

So, this regular expression would match the following e-mail addresses:

steve@somewhere.com
steve@host.somewhere.com
steve_smith@somewhere.com

However, it would fail to match e-mail addresses like

steve@aol
steve smith@aol

which is what you want.

If you want to exclude all e-mail addresses that do not end with a top-level domain name between two and three characters—such as .com, .net, and .ws—you would use this expression:

\S+@\S+\.\S{2,3}

The page in Listing 3.5 demonstrates how you would use this regular expression with the RegularExpressionValidator control.

Listing 3.5 RegularExpressionValidatorEmail.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "ThankYou.aspx" )
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionvalidatorEmail.aspx</title></head>
<body>

<form Runat="Server">

Email Address:
<br>
<asp:TextBox
 id="txtEmail"
 Columns="50"
 Runat="Server"/>

<asp:RegularExpressionValidator
 ControlToValidate="txtEmail"
 Text="Invalid Email Address!"
 ValidationExpression="\S+@\S+\.\S{2,3}"
 Runat="Server" />
<p>
<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>

</body>
</html>

Validating Usernames and Passwords

Typically, Web sites require you to enter a username and password containing only alphanumeric characters or the underscore character. You can perform this type of validation using a regular expression that looks like this:

\w+

This regular expression matches any expression that contains one or more word characters (a word character can be a letter, number, or the underscore character).

You also can specify a minimum and maximum length for a password by using a regular expression that looks like this:

\w{8,20}

This regular expression matches only expressions that are between 8 and 20 characters long.

Finally, some Web sites require you to use at least one number and one letter in your password. You can use the following regular expression to satisfy this requirement:

[a-zA-Z]+\w*\d+\w*

This regular expression requires you to enter at least one letter, followed by any number of word characters, followed by at least one number, followed by any number of word characters.

Listing 3.6 demonstrates how you can combine two RegularExpressionValidator controls and a RequiredFieldValidator control to validate a password. The Validation controls require you to enter a password that starts with at least one letter and contains one number and between 3 and 20 characters (special characters, such as # and ?, are not allowed).

Listing 3.6 RegularExpressionValidatorPassword.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "thankyou.aspx" )
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionValidatorPassowrd.aspx</title></head>
<body>

<form Runat="Server">

Password:
<br>
<asp:TextBox
 id="txtPassword"
 Columns="30"
 Runat="Server"/>

<asp:RequiredFieldValidator
 ControlToValidate="txtPassword"
 Display="Dynamic"
 Text="You must enter a password!"
 Runat="Server" />

<asp:RegularExpressionValidator
 ControlToValidate="txtPassword"
 Display="Dynamic"
 Text="Your password must contain between 3 and 20 characters!"
 ValidationExpression="\w{3,20}"
 Runat="Server" />

<asp:RegularExpressionValidator
 ControlToValidate="txtPassword"
 Display="Dynamic"
 Text="Your password must contain at least one number and letter!"
 ValidationExpression="[a-zA-Z]+\w*\d+\w*"
 Runat="Server" />
<p>
<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>
</body>
</html>

Validating Phone Numbers

Phone numbers are difficult to validate—especially when you take into consideration foreign area codes and phone number extensions. Even if you ignore these problems and concentrate on U.S. phone numbers without extensions, many different formats still are used when entering a phone number. For example, the following formats are all commonly used:

(555) 555-5555
555.555.5555
555 555-555

You can create a regular expression that matches all three of the preceding expressions, as follows:

\(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}

The page in Listing 3.7 illustrates how you can use this regular expression with RegularExpressionValidator.

Listing 3.7 RegularExpressionValidatorPhone.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "ThankYou.aspx" )
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionValidatorPhone.aspx</title></head>
<body>

<form Runat="Server">

Phone Number:
<br>
<asp:TextBox
 id="txtPhone"
 Columns="30"
 Runat="Server"/>

<asp:RegularExpressionValidator
 ControlToValidate="txtPhone"
 Display="Dynamic"
 Text="Invalid Phone Number!"
 ValidationExpression="\(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}"
 Runat="Server" />
<p>

<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>
</body>
</html>

Validating Web Addresses

You also might need to validate URLs that users enter into a form at your Web site. For example, you might have a registration form that contains a field for the URL of a user's home page.

You can use the following regular expression to check for a valid URL:

http://\S+\.\S+

This regular expression matches any string that begins with the characters http:// followed by one or more nonwhitespace characters, followed by a period, followed by one or more nonwhitespace characters.

The page in Listing 3.8 demonstrates how you can use this regular expression with RegularExpressionValidator.

Listing 3.8 RegularExpressionWeb.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "thankyou.aspx" )
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionValidatorWeb.aspx</title></head>
<body>

<form Runat="Server">

Enter the address
of your homepage:
<br>
<asp:TextBox
 id="txtHomepage"
 Columns="50"
 Runat="Server"/>

<asp:RegularExpressionValidator
 ControlToValidate="txtHomepage"
 Display="Dynamic"
 Text="Invalid URL!"
 ValidationExpression="http://\S+\.\S+"
 Runat="Server" />

<p>

<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>
</body>
</html> 

One problem with the code in Listing 3.8 concerns case-sensitivity. The RegularExpressionValidator control uses case-sensitive comparisons. So, the regular expression discussed in this section matches

http://www.superexpert.com

but does not match

Http://www.superexpert.com

Unfortunately, RegularExpressionValidator does not have a property that you can set to enable regular expression options such as the i option (an option which enables case-insensitive matches). You cannot use the i option inline because the syntax for doing so with JavaScript is different from the syntax for doing so with the .NET classes.

A not completely satisfactory workaround to this problem is illustrated by the page in Listing 3.9. The RegularExpressionValidator in this page performs a case insensitive match by using the i option. Furthermore, the RegularExpressionValidator disables client-side validation to prevent conflicts with JavaScript.

This is not a perfect workaround to the problem since the page must be submitted back to the server before the RegularExpressionValidator will validate the expression.

Listing 3.9 RegularExpressionIgnoreCase.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "thankyou.aspx" )
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionValidatorIgnoreCase.aspx</title></head>
<body>

<form Runat="Server">

Enter the address
of your homepage:
<br>
<asp:TextBox
 id="txtHomepage"
 Columns="50"
 Runat="Server"/>

<asp:RegularExpressionValidator
 ControlToValidate="txtHomepage"
 Display="Dynamic"
 Text="Invalid URL!"
 EnableClientScript="False"
 ValidationExpression="(?i:http://\S+\.\S+)"
 Runat="Server" />

<p>

<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>
</body>
</html>

Checking for Entry Length

You also can use RegularExpressionValidator to check whether a form field contains more than a certain number of characters. This type of validation is especially useful when you're working with MultiLine TextBox controls. Because a MultiLine TextBox control does not have a MaxLength property, there is nothing to prevent a user from typing any number of characters in the text box.

To check for a certain entry length, use regular expression quantifiers like this:

.{0,10}

This expression matches any entry (including spaces) that contains between 0 and 10 characters.

If you want to restrict the entry to a string of nonwhitespace characters that has a certain length, you would use a regular expression that looks like this:

\S{0,10}

The page in Listing 3.10 demonstrates how you can use this regular expression with RegularExpressionValidator.

Listing 3.10 RegularExpressionValidatorLength.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "ThankYou.aspx" )
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionValidatorLength.aspx</title></head>
<body>

<form Runat="Server">

Enter your last name:
<br>(no more than 10 characters)
<br>
<asp:TextBox
 id="txtLastname"
 Columns="50"
 Runat="Server"/>

<asp:RegularExpressionValidator
 ControlToValidate="txtLastname"
 Display="Dynamic"
 Text="Your last name can contain
    a maximum of 10 characters and no spaces!"
 ValidationExpression="\S{0,10}"
 Runat="Server" />
<p>

<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>

</body>
</html>

Validating ZIP Codes

You also can use the RegularExpressionValidator control to validate ZIP codes. For example, if you want to require that a ZIP code entered into a form field contains exactly five digits, you would use the following regular expression:

\d{5}

This expression matches strings that have no more or no fewer than five digits.

The page in Listing 3.11 demonstrates how you would use this regular expression with the RegularExpressionValidator control.

Listing 3.11 RegularExpressionValidatorZip.aspx

<Script Runat="Server">

Sub Button_Click( s As Object, e As EventArgs )
 If IsValid Then
  Response.Redirect( "ThankYou.aspx" ) 
 End If
End Sub

</Script>

<html>
<head><title>RegularExpressionValidatorZip.aspx</title></head>
<body>

<form Runat="Server">

ZIP Code:
<asp:TextBox
 id="txtZipCode"
 Columns="8"
 Runat="Server"/>

<asp:RegularExpressionValidator
 ControlToValidate="txtZipCode"
 Display="Dynamic"
 Text="Invalid ZIP Code!"
 ValidationExpression="\d{5}"
 Runat="Server" />

<p>

<asp:Button
 Text="Submit"
 OnClick="Button_Click"
 Runat="Server"/>

</form>

</body>
</html>

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020