articles

Home / DeveloperSection / Articles / CompareValidator Control in ASP.Net

CompareValidator Control in ASP.Net

Pushpendra Singh7325 10-Nov-2010

The CompareValidator control is used to compare the value of one input control to the value of another input control or to a fixed value.

<asp:CompareValidator ID="CompareValidator1" runat="server"  ErrorMessage="CompareValidator">
</asp:CompareValidator>


Properties:

ControlToCompare

The name of the control to compare with

ControlToValidate

The id of the control to validate

Error Message

The text to display in the page when validation fails. Note: This text will also be displayed in the validation control if the Text property is not set

ValueToCompare

A specified value to compare with

Code:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:CompareValidator ID="CompareValidator1" runat="server"
            ControlToCompare="TextBox1" ControlToValidate="TextBox2"
            ErrorMessage="Not Matched">
</asp:CompareValidator>

When we will not enter same value in both TextBox then error message will be displayed.

 

CompareValidator Control in ASP.Net

When we enter same value in both TextBox then page will execute

CompareValidator Control in ASP.Net

To compare with a fixed value you can write the value to compare in ValueToCompareproperty of CompareValidator.

<asp:CompareValidator ID="CompareValidator2" runat="server"
ControlToValidate="TextBox3" ErrorMessage="Enter your area Code"
ValueToCompare="20"></asp:CompareValidator>

Here in the above code we are comparing the value of TextBox3 with 20. By default this will check for equal value. You can also check it for greater than or less than by setting the Operator property to GreaterThan or LessThan, or what ever you want to as per you requirement.


Updated 04-Mar-2020

Leave Comment

Comments

Liked By