ASP.NET Validation

In this chapter, we will discuss about the data validation in the Web Forms. To perform validation, ASP.NET provides controls that automatically check user input and require no code. We can also create custom validation for our application.

ASP.NET validation controls

Following are the validation controls

ValidatorDescription
CompareValidatorIt is used to compare the value of an input control against a value of another input control.
RangeValidatorIt evaluates the value of an input control to check the specified range.
RegularExpressionValidatorIt evaluates the value of an input control to determine whether it matches a pattern defined by a regular expression.
RequiredFieldValidatorIt is used to make a control required.
ValidationSummaryIt displays a list of all validation errors on the Web page.

ASP.NET CompareValidator Control

This validator evaluates the value of an input control against another input control on the basis of specified operator.

We can use comparison operators like: less than, equal to, greater than etc.

Note: If the input filed is empty, no validation will be performed.

CompareValidator Properties

PropertyDescription
AccessKeyIt is used to set keyboard shortcut for the control.
TabIndexThe tab order of the control.
BackColorIt is used to set background color of the control.
BorderColorIt is used to set border color of the control.
BorderWidthIt is used to set width of border of the control.
FontIt is used to set font for the control text.
ForeColorIt is used to set color of the control text.
TextIt is used to set text to be shown for the control.
ToolTipIt displays the text when mouse is over the control.
VisibleTo set visibility of control on the form.
HeightIt is used to set height of the control.
WidthIt is used to set width of the control.
ControlToCompareIt takes ID of control to compare with.
ControlToValidateIt takes ID of control to validate.
ErrorMessageIt is used to display error message when validation failed.
OperatorIt is used set comparison operator.

Example

Here, in the following example, we are validating user input by using CompareValidator controller. Source code of the example is given below.

// compare_validator_demo.aspx

Output:

ASP Validation 1
ASP Validation 2