Using the ASP.NET CompareValidator Control
The CompareValidator control can be used to perform the following validation tasks:
Check the data type of a form field.
Compare the value of a form field against the value of another form field.
Compare the value of a form field against a fixed value.
In the following sections, you’ll see sample code for performing all three validation tasks.
The CompareValidator control includes the following properties:
ControlToValidate – The id of the form field being validated.
Text – The error message displayed when validation fails.
ControlToCompare – When comparing the value of one form field against another, use this property to provide the ID of the form field being compared.
ValueToCompare – When comparing the value of a form field against a fixed value, use this property to set the fixed value.
Type – The type of comparison to perform. Possible values are Integer, String, Date, Double, and Currency.
Operator – The comparison operation to perform. Possible values are Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.
Performing a Data Type Check
You can use the CompareValidator to perform a data type check. For example, the following page verifies that a date value has been entered into a TextBox named txtBirthdate.
Notice that you must set both the Type and Operator properties when performing a data type check. The Operator property must be set to the value DataTypeCheck.
Comparing Against a Fixed Value
You also can use the CompareValidator control to compare the value of a form field against a fixed value. For example, the following page compares the value entered into a TextBox named txtNewBid against a fixed value which represents the previous bid.
Comparing Two Form Fields
Finally, you can use the CompareValidator control to compare one form field against another form field. You do this by using the ControlToCompare property. For example, the following page contains two TextBox controls which represent an event start date and an event end date. The CompareValidator control is used to check whether or not the event end data happens after the event start date.