Powered by Blogger.

Saturday, February 15, 2014

Compare validator example in asp.net

In this post we will discuss about one example on how to use compare validator in Asp.Net. Also you can check out my previous posts on:

- Boxing and Unboxing in C#.Net

- Data files and Log files in sql server 2008

- If Else statements in JavaScript Example

Here in this example, we will take 2 textboxes on for start serial number and other on is the end serial number. And our validation will be start serial number should be smaller than end serial number. Below is the full code:

.Aspx code:
<head id="Head1" runat="server">
    <title>Compare validator example in asp.net</title>
    <form id="form1" runat="server">
        Start Serial Number:
        <asp:TextBox ID="txtSerialFrom" runat="server"></asp:TextBox><br />
        End Serial Number:
        <asp:TextBox ID="txtSerialTo" runat="server"></asp:TextBox><br />
        <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="End Serial number should be greater than start serial number"
            ControlToValidate="txtSerialTo" ControlToCompare="txtSerialFrom" Type="Integer"
            Operator="GreaterThan" ValidationGroup="Group1" ForeColor="Red">
        </asp:CompareValidator><br />
        <asp:Button ID="btnCheck" runat="server" Text="Check" ValidationGroup="Group1" />


Here the property Operator will take values such as: GreaterThan, Equal, DataTypeCheck, GreaterThanEqual, LessThan, LessThanEqual, NotEqual.

And you can use compare validator for Currency, Date, Double, Integer and String which is set in the Type property.

If you will enter higher value in first textbox than the value in 2nd textbox the error message will appear like below: