Compare Validaor Example
Compare Validaor Example
CompareValidator Control is used to compare the value of one control with the value of another control
or constant value. The comparison operation can any of the following.
1. Equal
2. GreaterThan
3. GreaterThanEqual
4. LessThan
5. LessThanEqual
6. NotEqual
7. DataTypeCheck
The following are the properties that are specific to the compare validator:
Note: SetFocusOnError property is supported by all validation controls. If this property is set to true,
then the control will automatically receive focus, when validation fails.
Compare Validator Example
Compare Validator.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="CompareValidator.aspx.cs"
Inherits="WebApplication1.CompareValidator" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<b>Password</b>
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"
Width="150px" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<b>Retype Password</b>
</td>
<td>
<asp:TextBox ID="txtRetypePassword"
runat="server" Width="150px" TextMode="Password"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ErrorMessage="Password Does Not Match!"
ForeColor="Red"
ControlToValidate="txtRetypePassword"
ControlToCompare="txtPassword"
Type="String" Operator="Equal"></asp:CompareValidator>
</td>
</tr>
<tr>
<td>
<b>Date of Application</b>
</td>
<td>
<asp:TextBox ID="txtDate" runat="server"
Width="150px"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator2"
runat="server"
ErrorMessage="Application Date Must Be
Greater Than 01/01/2017!" ForeColor="Red" ControlToValidate="txtDate"
ValueToCompare="01/01/2017" Type="Date"
Operator="GreaterThan"></asp:CompareValidator>
</td>
</tr>
<tr>
<td>
<b>Age</b>
</td>
<td>
<asp:TextBox ID="txtAge" runat="server"
Width="150px"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator3"
runat="server"
ErrorMessage="Age Must Be an Integer
Value!" ForeColor="Red"
ControlToValidate="txtAge" Type="Integer"
Operator="DataTypeCheck"
SetFocusOnError="true"></asp:CompareValidator>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSave" runat="server"
Text="Save" Width="100px" OnClick="btnSave_Click" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblStatus" runat="server"
Text="" Font-Bold="true"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
CompareValidator.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class CompareValidator : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{