Home > Articles > Programming > ASP .NET

This chapter is from the book

Using Validation Controls

All Validation controls share similar properties. At a minimum, each control should specify two properties (not including runat="server"). First, they all must contain the ControlToValidate property, which specifies the name of the server control that this validator should watch over. Second, each control must have an ErrorMessage property that tells ASP.NET what message to display to the user if the validation fails. There are a few additional properties as well, which will be covered later today in "Customizing Validation."

Let's go back to Listing 7.1 and revise it to use Validation controls. First, let's examine what types of validation you'll need.

For your first name and last name text boxes, you'll need to ensure that the user enters data—any data at all, just as long as there's text in the boxes. This validation calls for a RequiredFieldValidator control. For an added security step, you'll also make sure that the first and last names aren't the same. This prevents users from simply typing a string of characters (such as "asdf") into each box. You'll use a CompareValidator for this.

For the e-mail box, you'll need to ensure that the e-mail address is in a valid format, such as somename@somesite.com. Again, this is to prevent users from entering random strings of characters. The RegularExpressionValidator control will perform this functionality. The ZIP code and phone number text boxes will also need to be checked for valid formats. For instance, the ZIP code must be five digits, without letters, and the phone number (for our purposes) must be in the format xxx-xxxx.

Finally, let's assume that you want to allow only users from a certain region of the United States (a certain range of ZIP codes) to submit your form. This type of validation can be performed with the RangeValidator control. Listing 7.5 shows the UI portion of this page.

Listing 7.5 The UI Portion of Your Enhanced User Form

1: <html><body>
2:  <form runat="server">
3:   <asp:Label id="lblHeader" runat="server"
4:    Height="25px" Width="100%" BackColor="#ddaa66"
5:    ForeColor="white" Font-Bold="true"
6:    Text="A Validation Example" />
7:   <asp:Label id="lblMessage" runat="server" /><br>
8:   <asp:Panel id="Panel1" runat="server">
9:    <table>
10:    <tr>
11:    <td width="100" valign="top">
12:     First and last name:
13:    </td>
14:    <td width="300" valign="top">
15:     <asp:TextBox id="tbFName" runat="server" />
16:     <asp:TextBox id="tbLName" runat="server" />
17:     <br>
18:     <asp:RequiredFieldValidator runat="server"
19:      ControlToValidate="tbFName"
20:      ErrorMessage="First name required"/><br>
21:     <asp:RequiredFieldValidator runat="server"
22:      ControlToValidate="tbLName"
23:      ErrorMessage="Last name required"/><br>
24:     <asp:CompareValidator runat="server"
25:      ControlToValidate="tbFName"
26:      ControlToCompare="tbLName"
27:      Type="String"
28:      Operator="NotEqual"
29:      ErrorMessage="First and last name
30:     cannot be the same" />
31:    </td>
32:    </tr>
33:    <tr>
34:    <td valign="top">Email (.com's only):</td>
35:    <td valign="top">
36:     <asp:TextBox id="tbEmail"
37:      runat="server" /><br>
38:     <asp:RegularExpressionValidator
39:      runat="server"
40:      ControlToValidate="tbEmail"
41:      ValidationExpression="\w+\@\w+\.com"
42:      ErrorMessage="That is not a valid email"
43:     />
44:    </td>
45:    </tr>
46:    <tr>
47:    <td valign="top">Address:</td>
48:    <td valign="top">
49:     <asp:TextBox id="tbAddress"
50:      runat="server" />
51:    </td>
52:    </tr>
53:    <tr>
54:    <td valign="top">City, State, ZIP (5-digit):</td>
55:    <td valign="top">
56:     <asp:TextBox id="tbCity"
57:      runat="server" />,
58:     <asp:TextBox id="tbState" runat="server"
59:      size=2 />&nbsp;
60:     <asp:TextBox id="tbZIP" runat="server"
61:      size=5 /><br>
62:     <asp:RegularExpressionValidator
63:      runat="server"
64:      ControlToValidate="tbZIP"
65:      ValidationExpression="[0-9]{5}"
66:      ErrorMessage="That is not a valid ZIP" />
67:     <br>
68:     <asp:RangeValidator runat="server"
69:      ControlToValidate="tbZIP"
70:      MinimumValue="00000" MaximumValue="22222"
71:      Type="String"
72:      ErrorMessage="You don't live in the
73:     correct region" />
74:    </td>
75:    </tr>
76:    <tr>
77:    <td valign="top">Phone (<i>xxx-xxxx</i>):</td>
78:    <td valign="top">
79:     <asp:TextBox id="tbPhone" runat="server"
80:      size=11 /><br>
81:     <asp:RegularExpressionValidator
82:      runat="server"
83:      ControlToValidate="tbPhone"
84:      ValidationExpression="[0-9]{3}-[0-9]{4}"
85:      ErrorMessage="That is not a valid phone"
86:     />
87:    </td>
88:    </tr>
89:    <tr>
90:    <td colspan="2" valign="top" align="right">
91:     <asp:Button id="btSubmit" runat="server"
92:      text="Add" />
93:    </td>
94:    </tr>
95:    </table>
96:   </asp:Panel>
97:  </form>
98: </body></html>

That's quite a bit of code, but there are only a few things you need to examine. The rest is plain HTML. First, let's take note of what this page doesn't do. The e-mail, city, state, ZIP, and phone controls do not have corresponding RequiredFieldValidators, essentially making them optional. If the user enters nothing in these fields, validation will pass because none of the other Validation controls care if a field is empty. Even if the field is blank, the control's IsValid property will return true. Next, note that the form only accepts certain types of e-mail addresses, ZIP codes, and phone numbers. The e-mail addresses can only end in .com. The ZIP code can only be five digits (some postal codes use nine digits, xxxxx-xxxx). And phone numbers can only contain seven digits, with a dash between the third and fourth digits. These validation rules can be quite limiting, but they're fine for the purposes of this lesson. In a real-world situation, you'd probably want to make your rules more general.

Let's look at lines 18–30. You have two instances of RequiredFieldValidator, on lines 18 and 22. These controls make sure that the user enters some data into the first name and last name text boxes, respectively. You've already seen this control used earlier today. These lines contain only the two required properties, ControlToValidate and ErrorMessage.

CompareValidator on line 24 can compare the value of one server control to a constant, or to another server control. Here, you're comparing tbFName and tbLName to make sure they aren't the same. The Type property tells ASP.NET what kind of values you're comparing, such as String, Double, DateTime, and so on. The Operator specifies what type of comparison should be made. In this case, you're comparing two strings from two text boxes, and you want to make sure the values aren't equal. Again, you have the standard ControlToValidate and ErrorMessage properties. Tables 7.2 and 7.3 list the valid operators and types used with the CompareValidator.

Table 7.2 Operators for Use with the CompareValidator's Operator Property

Operator

Description

DataTypeCheck

Checks if the data is a certain data type (string, integer, and so on)

Equal

Checks for equality

GreaterThan

Checks for greater than

GreaterThanEqual

Checks for greater than or equal to

LessThan

Checks for less then

LessThanEqual

Checks for less than or equal to

NotEqual

Checks for inequality


Table 7.3 Types for Use with the CompareValidator's Type Property

Type

Description

Currency

Currency values

Date

Date values

Double

Double values (floating point)

Integer

Integer values

String

String values


NOTE

To compare against a constant value, change ControlToCompare to ValueToCompare. For example, the following CompareValidator checks if the value entered matches the string "Chris." If it does, validation fails and an error message is displayed:

<asp:CompareValidator runat="server"
 ControlToValidate="tbFName"
 ValueToCompare="Chris"
 Type="String"
 Operator="NotEqual"
 ErrorMessage="Your first name cannot be the same as mine"/>

If you just wanted to check if the user input is a valid data type, you could set the Operator property of the CompareValidator to DataTypeCheck and leave the ControlToCompare property out. Be careful with this operator, though. In a Web form, all inputs evaluate to strings, so you might not get the correct validation. For example, the following CompareValidator will be satisfied if the user enters 76.7878:

<asp:CompareValidator runat="server"
 ControlToValidate="tbFName"
 Type="String"
 Operator="DataTypeCheck"
 ErrorMessage="You must enter a string value" />

Note that when you have two or more Validation controls referencing one server control, all conditions must be satisfied for the input to be valid. Therefore, the first name and last name boxes must both be filled out, and they cannot contain the same text.

On line 38, you declare a RegularExpressionValidator control, which checks if the user input matches a pattern of characters. The only new property in this control is ValidationExpression on line 41, which specifies the regular expression that should be used to validate the input. In this case, the string \w+\@\w+\.com means one or more word characters (in other words, a letter), followed by the @ symbol, followed by one or more word characters, followed by .com. For more information, refer to the "Regular Expressions" section later today.

On line 62, you have another RegularExpressionValidator that checks if a proper ZIP code was entered. The string [0-9]{5} means five of any of the characters 0 through 9.

On line, 68 you have a RangeValidator control, which checks if the specified server control's value falls between the limits you've specified. This is so you can limit the form to people in particular regions of the U.S. You can even compare dates and strings with this control! Line 70 specifies the MinimumValue and MaximumValue properties that set the boundaries for your ZIP codes. You set the Type property to String so that the ZIP codes will be evaluated properly. (If you used Double or Integer, the string 00001 would evaluate to 1, which is not what you want.)

Finally, on line 81, you have another RegularExpressionValidator. This control is used to validate the user's phone number. It ensures that the number is seven digits long. The ValidationExpression string [0-9]{3}-[0-9]{4} will match three of any of the characters 0 through 9, followed by a dash, followed by four of any of the characters 0 through 9. This can represent any U.S. 7-digit phone number.

TIP

You can specify multiple patterns to match in a RegularExpressionValidator by using the | symbol (meaning "or") in the ValidationExpression property. For example, the following string matches any phone number that has seven digits with dashes, 10 digits with dashes, or 10 digits with no dashes:

([0-9]{3}-[0-9]{4})|([0-9]{3}-[0-9]{3}-[0-9]{4})|([0-9]{10})
The user could enter any of the following and it would be valid:
458-9865
625-458-9865
6254589865

Experiment with the form to produce different outputs. Test the RegularExpressionValidator controls by entering both values that match the pattern and values that don't. Also, try entering values in some fields but leaving others blank, and then submit the form. Figure 7.4 shows an attempt to enter some invalid data. Note the error messages next to the offending text boxes. Figure 7.5 shows the page when everything has been entered correctly.

Figure 7.4 A test of the validation form, with errors.

CAUTION

Don't forget that only the RequiredFieldValidator control considers a blank field invalid. All of the other controls accept empty fields. This means that despite the e-mail address field being left blank, the check by the RegularExpressionValidator will pass and this control's IsValid property will return true. The validator won't stop the form from being processed even if there's no data in the field.

Therefore, you must use the RequiredFieldValidator control in addition to the other validators if you want to check for actual values.

Validating on the Server

Client-side validation is a wonderful tool that saves you a lot of headaches. But you still have to handle the validation yourself on the server side. Just because a form is invalid doesn't mean ASP.NET won't execute your code. Therefore, you have to add some checks to your methods.

The simplest way to check for validity in your form is to check the Page object's IsValid property. If all the Validation controls are satisfied with the input, this property is true; if any of the Validation controls are invalid, it's false. Thus, you could simply check this property and decide whether or not to execute your code. For example, Listing 7.6 shows a possible code declaration block used with Listing 7.5.

Figure 7.5 A test of the validation form, without errors.

Listing 7.6 Testing Page Validity

1: <%@ Page Language="VB" %>
2:
3: <script runat="server">
4:  sub Submit(obj as object, e as eventargs)
5:   if Page.IsValid then
6:    lblMessage.Text = "Success!"
7:   else
8:    lblMessage.Text = "One of the fields is invalid"
9:   end if
10:  end sub
11: </script>
12: ...
13: ...
14:    <tr>
15:    <td colspan="2" valign="top" align="right">
16:     <asp:Button id="btSubmit" runat="server"
17:      text="Add" 
18:      OnClick="Submit" />
19:    </td>
20:    </tr>
21:    </table>
22:   </asp:Panel>
23:  </form>
24: </body></html>

The Submit method on line 5 checks, with one property, if all of the Validation controls are valid. You can then execute your code or not, depending on your needs. If the controls are valid, you could insert the data into a database or e-mail the user—whatever you would normally do during a form submission. If the controls are invalid, you should display a message to the user explaining why the submission failed—why client-side validation passed but server-side didn't.

The Validators collection contains references to all of the Validation controls on the page. You can loop through this collection to determine individual control validity:

1: sub Submit(obj as object, e as eventargs)
2:  if Page.IsValid then
3:   lblMessage.Text = "Success!"
4:  else
5:   dim objValidator as Ivalidator
6:   For Each objValidator in Validators
7:    if not objValidator.IsValid then
8:    lblMessage.Text += objValidator.ErrorMessage
9:    end if
10:   Next
11:  end if
12: end sub

This code loops through each Validation control in Validators and displays the error messages for each invalid control. You can also check the IsValid property on any control in particular by referencing its name. To do this, you must assign the id property for each Validation control, which you haven't done so far. For example, if the RegularExpressionValidator for the e-mail text box had the id valEmail, the following code would display the error message if e-mail validation failed:

if not valEmail.IsValid then
 lblMessage.Text =+ valEmail.ErrorMessage
end if

Disabling Validation

There are several ways to disable validation without having to delete your Validation controls. The first method is to simply set the Enabled property of each control to false:

<asp:RegularExpressionValidator runat="server"
 ControlToValidate="tbZIP"
 Enabled="false" />

This prevents the control from sending any output to the client and thus validating the specified control.

You can also disable all validation on the client side by setting the clienttarget property of the <%@ Page %> directive to downlevel:

 <%@ Page Language="VB" clienttarget="downlevel" %>

This command makes ASP.NET think that it's dealing with an older browser that doesn't support DHTML. In effect, all DHTML events are disabled, including client-side validation.

CAUTION

Only use this option as a last resort. Disabling all DHTML events means that there will be no dynamic client-side handling at all.

For example, ASP.NET will no longer use the <style> tag to change Web controls' appearance. All CSS attributes are disabled.

Regular Expressions

A regular expression is a string that contains special symbols (or sequences of symbols) that can be used to match patterns of characters. For example, you've probably seen an asterisk used when performing searches. The following string means "display all files in the current directory":

dir *.*

This is a form of regular expression. The asterisk is a wildcard that can be used to represent any other character. It matches a specified pattern of filenames—specifically, all files that contain a string, followed by a period, followed by another string. The key to learning regular expressions is finding out how to match patterns of text.

Regular expressions are difficult to master and their syntax is very complex, so today's lesson won't go into any depth. Creating or deciphering expressions involves learning which characters have special meaning in the language and how to specify normal characters. Deciphering a few examples may help you to understand expressions that you come across. Table 7.4 shows the most common characters used with regular expressions. These characters by themselves are useful. However, it's when they're combined that the true power of regular expressions shines through.

Table 7.4 Regular Expression Language Elements

Character(s)

Meaning

Regular characters

All characters other than ., $, ^, {, [, (, |, ), *, +, ?, and \ are matched to themselves. In other words, the regular expression hello matches any string with the text hello. These exception characters all have special meanings.

.

Matches any one character.

$

Matches patterns at the end of a string. For example, $hello will match the string hello only when it's at the end of a string. It will match I said hello, but not Did you say hello?.

^

Matches patterns at the beginning of a string. Similar to $. When used in square brackets, ^ means "not." For example, [^aeiou] means "match any one character that is not in the given list."

{}

Used to match a certain quantity of characters. For example, hello{2} matches the string hellohello. aye{2} matches ayeaye.

[]

Used to match any one of a group of characters. For example, [aeiou] matches any one of the letters a, e, i, o, or u. You can also use the dash to specify ranges. [a-z] matches any one of the lowercase letters a through z.

()

Used for grouping strings. Similar to using parentheses to change the order of precedence in operations.

|

Means logical or. (hello)|(HELLO) means "match either hello or HELLO."

*

Match zero or more matches. h*ello means "match zero or more occurrences of the letter h, followed by the letters ello."

+

Match one or more occurrences. h+ello would match hello and hhhhello, but not ello.

?

Match zero or one occurrences. h?ello matches ello and hello, but not hhello.

\

An escape character. When any of the previous special characters are preceded by the backslash, they're matched literally. For example, h\*ello matches the string h*ello but not h\\\ello or hhhello. Additionally, certain normal characters have special meaning when preceded by a backslash.


When you're deciphering regular expressions, it helps to look for the special characters. Because they can be grouped, examine the characters between special characters as well. For example, the expression href\\s*=\\s*(\"([^\"]*)\"|(\\S+)) means href followed by zero or more white spaces (\s*), then by =, then by zero or more white spaces again. This is then followed by a double quote (\"), then by zero or more occurrences of anything that's not a double quote ([^\"]*), followed by a double quote or one or more non-white space characters (\S+). This string can be used to find anchors in an HTML page, such as href = "blah: and href="hey".

Note that the escape character (\) is used in several places where it isn't necessary. For example, " has no special meaning. It matches the string ". However, when in doubt, it's usually safe to use the escape character.

The regular expression [0-9]{5}-[0-9]{4}|[0-9]{5} means any five characters between 0–9, followed by a dash, followed by any four characters between 0–9, or any five characters between 0–9. Values like 90210 or 83647-1422 will pass, whereas values like 9021A or 902 will not.

Regular expressions are commonly used throughout computing to match patterns of text. For more information, check out the .NET Framework SDK documentation, or the following online resources:

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