The CompareValidator control compares a value in one control with a fixed value or, more commonly, a value in another control.  You can use this control to check that two text boxes have the same data or that a value in one text box doesn’t exceed a maximum value established in another. The CompareValidator control, like the RangeValidator control, has a Type property that determines the type of data you are comparing. The control also exposes the ValueToCompare and ControlToCompare properties, which allow you to compare the value of the input control with a constant value or the value of another input control, respectively. You can use only one of these two properties. By using the Operator property you can specify the type of comparison you want to do. The available values are Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck. The DataTypeCheck value forces the validation control to check that the input has the required data type (specified through the Type property), without performing any additional comparison.

The next example compares an input with a value in order to ensure that the specified number is greater than or equal to 1:

 

<asp:TextBox runat=”server” ID=”Number” />

<asp:CompareValidator runat=”server” Display=”dynamic”

ControlToValidate=”Number” ValueToCompare=”1″

ErrorMessage=”You must enter a number of tickets greater than 0″

Type=”Integer” Operator=”GreaterThanEqual”>*

</asp:CompareValidator>

 

The next example compares the input values in two password text boxes to ensure that their value is the same:

 

<asp:TextBox runat=”server” TextMode=”Password” ID=”txtPassword1″ />

<asp:TextBox runat=”server” TextMode=”Password” ID=”txtPassword2″ />

<asp:CompareValidator runat=”server”

ControlToValidate=”txtPassword2″ ControlToCompare=”txtPassword1″

ErrorMessage=”The passwords don’t match”

Type=”String” Display=”dynamic”>

<img src=”imgError.gif” alt=”The passwords don’t match” />

</asp:CompareValidator>