ASP.NET CompareValidator Control

Definition and usage

The CompareValidator control is used to compare the value entered by the user into the input control with the value entered into another input control or a constant value.

Note:No validation function is called if the input control is empty, and validation will succeed. Use the RequiredFieldValidator control to make the field a required field.

Property

Property Description
BackColor The background color of the CompareValidator control.
ControlToCompare The input control to be compared with the input control to be validated.
ControlToValidate The ID of the input control to be validated.
Display

The display behavior of error information in the validation control.

Valid values are:

  • None: Validation messages are never displayed inline.
  • Static: Space is allocated in the page layout for displaying validation messages.
  • Dynamic: A space is dynamically added to the page to display the validation message if the validation fails.
EnableClientScript A boolean value that specifies whether client-side validation is enabled.
Enabled A boolean value that specifies whether the validation control is enabled.
ErrorMessage

The text displayed in the ValidationSummary control when the validation fails.

Note: If the Text property is not set, this text will be displayed in the validation control.

ForeColor The foreground color of the control.
id The unique ID of the control.
IsValid A boolean value indicating whether the input control specified by ControlToValidate passes the validation.
Operator

The type of comparison operation to be performed.

The operators are:

  • Equal
  • GreaterThan
  • GreaterThanEqual
  • LessThan
  • LessThanEqual
  • NotEqual
  • DataTypeCheck
runat Specifies that the control is a server control. Must be set to "server".
Text The message displayed when the validation fails.
Type

Specifies the data type of the value to be compared.

Types include:

  • Currency
  • Date
  • Double
  • Integer
  • String
ValueToCompare A constant value that needs to be compared with the value entered by the user into the validated input control.

Example

CompareValidator
In this example, we declare two TextBox controls, one Button control, and one CompareValidator control in the .aspx file. If the validation fails, "Validation Failed!" will be displayed with a yellow background and red text in the CompareValidator control.
CompareValidator 2
In this example, we declare two TextBoxes, one ListBox control, one Button control, and one CompareValidator control in the .aspx file. The check_operator() function sets the operator selected in the ListBox control to the operator of the CompareValidator control and then validates the CompareValidator control. If the validation fails, "Validation Failed!" will be displayed with a yellow background and red text in the CompareValidator control.