In this article I will explain with an example, how to use CompareValidator in ASP.Net.
 
 
HTML Markup
The following HTML Markup consists of two ASP.Net TextBox, an ASP.Net RequiredFieldValidator, an ASP.Net CompareValidator and an ASP.Net Button control.
Following are the properties used in the validators.
RequiredFieldValidator
1. ControlToValidate – Sets the control ID to validate. Here ID of the Password TextBox is set.
2. ErrorMessage – Sets the error message to be displayed when validation fails. Here ID of the Password TextBox is set.
3. Display – Sets the display behavior of the error message. The default value is Static. In this case it is Dynamic.
4. ForeColor – Sets the Text color of the error message. In this case it is Red.
 
CompareValidator
1. ControlToCompare – Sets the control ID with which to compare. Here ID of the Password TextBox is set.
2. ControlToValidate – Sets the control ID to validate. Here ID of the Confirm Password TextBox is set.
3. ErrorMessage – Sets the error message to be displayed when validation fails.
4. Display – Sets the display behavior of the error message. The default value is Static. In this case it is Dynamic.
5. ForeColor – Sets the Text color of the error message. In this case it is Red.
 
When the Submit Button is clicked, the values of the Password and Confirm Password TextBoxes are compared by the ASP.Net CompareValidator and if the values do not match error message is displayed.
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>Password</td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /><br/>
            <asp:RequiredFieldValidator runat="server" ControlToValidate="txtPassword"
                ErrorMessage="Password is required." ForeColor="Red" Display="Dynamic">
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>Confirm Password</td>
        <td>
            <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" /><br/>
            <asp:CompareValidator runat="server" ControlToCompare="txtPassword" ControlToValidate="txtConfirmPassword"
                ErrorMessage="Passwords do not match." ForeColor="Red" Display="Dynamic">
            </asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td></td>
        <td><asp:Button Text="Submit" runat="server" /></td>
    </tr>
</table>
 
 
Screenshot
ASP.Net CompareValidator Example
 
 
Demo
 
 
Downloads