Search code examples
c#asp.netcomparevalidator

How to use compare validator to compare the data between two dropdownlists values?


I have two DropDownLists populated with Year-Dates, and I want to show an error message in the case where the second ddls value is less than the first ddls value.

This is the code I have used so far, and it doesn't work:

  <asp:CompareValidator 
       ID="cvEndYear2" Operator="GreaterThan" runat="server" CssClass="text-danger" 
       ValidationGroup="Save" ControlToValidate="ddlEndYear" Display="Dynamic" 
       ValueToCompare="ddlStartYear" ErrorMessage="Greater Than" SetFocusOnError="true">
  </asp:CompareValidator>

Solution

  • You have to specify the ControlToCompare and the Operator:

    <asp:CompareValidator 
       ID="cvEndYear2" Operator="GreaterThan" runat="server" CssClass="text-danger" 
       ValidationGroup="Save" 
       ControlToValidate="ddlEndYear" Display="Dynamic" 
       ControlToCompare="ddlStartYear"
       Operator="GreaterThanEqual"
       Type="Integer"
       ErrorMessage="The end year must be greater/equal the start year" SetFocusOnError="true">
    </asp:CompareValidator>