Asp.Net CompareValidator With Date Example

Asp.Net CompareValidator Example To Compare Or Validate Dates Or TextBox Values

To configure CompareValidator we need to assign ControlToCompare, ControlToValidate,Operator properties.

Asp.Net comparevalidator with dates example
For example We can use comparevalidator to compare values entered in password and confirm password textboxes which needs to be same,
And using it we don't need to wtite any code to check whether password in both textboxes are equal or not.

I have placed a textbox txtPwd for entering password and another textbox txtRePwd for re entering password.

   1:  <tr>
   2:  <td>Password:</td>
   3:  <td><asp:TextBox ID="txtPwd" runat="server"
   4:                   TextMode="Password">
   5:      </asp:TextBox>
   6:  </td>
   7:  </tr>
   8:  <tr>
   9:  <td>Confirm Password:</td>
  10:  <td><asp:TextBox ID="txtRePwd" runat="server"
  11:                   TextMode="Password">
  12:      </asp:TextBox>
  13:  </td>
  14:  <td>
  15:  <asp:CompareValidator ID="CompareValidator1" 
  16:       runat="server" 
  17:       ControlToCompare="txtRePwd" 
  18:       ControlToValidate="txtPwd" 
  19:       Operator="Equal" 
  20:       ErrorMessage="Password and confirm 
  21:                     password do not match" 
  22:       SetFocusOnError="True">
  23:  </asp:CompareValidator>
  24:  </td>
  25:  </tr>

We can also use comparevalidator to validate dates.
For validation we need to define Type property of comparevalidator to Date.

   1:  <asp:CompareValidator ID="CompareValidator2" 
   2:       runat="server"
   3:       ControlToCompare="txtLastDate"
   4:       ControlToValidate="txtRegDate" 
   5:       ErrorMessage="Please enter registration 
   6:                     date earlier then last date"
   7:       Operator="LessThanEqual" Type="Date" 
   8:       ValueToCompare="<%= txtLastDate.Text.ToShortString() %>">*
   9:  </asp:CompareValidator>

Hope this helps.

If you like this post than join us or share

Find More Articles