As you’ve probably noticed, the CompareValidator control differs very little from
the RequiredFieldValidator control:
File: Login.aspx (excerpt)
<asp:RequiredFieldValidator id="confirmPasswordReq" runat="server"
ControlToValidate="confirmPasswordTextBox"
ErrorMessage="Password confirmation is required!"
SetFocusOnError="True" Display="Dynamic" />
<asp:CompareValidator id="comparePasswords" runat="server"
ControlToCompare="passwordTextBox"
ControlToValidate="confirmPasswordTextBox"
ErrorMessage="Your passwords do not match up!"
Display="Dynamic" />
The only difference is that in addition to a ControlToValidate property, the
CompareValidator has a ControlToCompare property. We set these two properties
to the IDs of the controls we want to compare. So, in our example, the
ControlToValidate property is set to the confirmPasswordTextBox, and the
ControlToCompare property is set to the passwordTextBox.
The CompareValidator can be used to compare the value of a control to a fixed
value, too. CompareValidator can check whether the entered value is equal to,
less than, or greater than, any given value. As an example, let’s add an age field
to our login form:
File: Login.aspx (excerpt)
<!-- Age -->
<p>
Age:<br />
<asp:TextBox id="ageTextBox" runat="server" />
<asp:RequiredFieldValidator id="ageReq" runat="server"
ControlToValidate="ageTextBox"
ErrorMessage="Age is required!"
SetFocusOnError="True" Display="Dynamic" />
<asp:CompareValidator id="ageCheck" runat="server"
Operator="GreaterThan" Type="Integer"
ControlToValidate="ageTextBox" ValueToCompare="15"
ErrorMessage="You must be 16 years or older to log in" />
</p>
In this case, the CompareValidator control is used to check that the user is old
enough to log in to our fictitious web application. Here, we set the Operator
property of the CompareValidator to GreaterThan. This property can take on
any of the values Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,
232
Chapter 6: Using the Validation Controls