Home > Articles

  • Print
  • + Share This
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:

  • + Share This
  • 🔖 Save To Your Account