In this article I’m going to explain how to
use CompareFieldValidator control in ASP.NET.
CompareFieldValidator
control:
The CompareFieldValidator
control is used to compare
the value of one input control to the value of another input control or to a
fixed value.
I’ve written
few articles about validation in ASP.NET. You may refer these articles,
How to use RequiredFieldValidator control in ASP.NET
How to use RangeValidator control in ASP.NET
How to use RegularExpressionValidator
control in ASP.NET
Here I’ll show you how to use CompareFieldValidator
control. In this demo I’ve used two
TextBox controls will be validated by CompareFieldValidator.
Properties:
ü ControlToCompare:
Gets or
sets the input control to compare with.
ü ControlToValidate: Gets or sets the input control
to validate.
ü Display: Gets or sets the display
behavior of the error message in a validation control.
ü ErrorMessage: Gets or sets the text for the
error message displayed in a ValidationSummary control when validation fails.
ü SetFocusOnError: Gets or sets a value that
indicates whether focus is set to the control specified by the ControlToValidate property when validation fails.
ü ValidationGroup: Gets or sets the name of the
validation group to which this validation control belongs.
Designer
source code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Compare
Filed Validator Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID="txtName"
runat="server"
ValidationGroup="Submit"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td>
User-ID :
</td>
<td>
<asp:TextBox ID="txtUserID"
runat="server"
ValidationGroup="Submit"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Confirm
User-ID :
</td>
<td>
<asp:TextBox ID="txtConfirmUserID"
runat="server"
ValidationGroup="Submit"></asp:TextBox>
</td>
<td>
<asp:CompareValidator ID="password_CompareValidator"
runat="server"
ErrorMessage="User-ID
is not match"
ControlToCompare="txtUserID"
ControlToValidate="txtConfirmUserID"
Display="Dynamic"
ForeColor="Red">
</asp:CompareValidator>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="Submit" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>