HI WELCOME TO SIRIS

Validate ListBox and DropDown List using Required Field Validator

In Asp.net, sometimes we need to validate ListBox and DropDown List using Required field validator. It is tricky and avoids the use of JavaScript function to validate ListBox and DropDown List. Here I am sharing the code.

Validate DropDown List and ListBox

  1. <form id="form1" runat="server">
  2. <div>
  3. <asp:ListBox ID="lstboxCity" runat="server" Width="200px" SelectionMode="Multiple">
  4. <asp:ListItem Value="1">Delhi</asp:ListItem>
  5. <asp:ListItem Value="2">Noida</asp:ListItem>
  6. <asp:ListItem Value="3">Gurgaon</asp:ListItem>
  7. <asp:ListItem Value="4">Mumbai</asp:ListItem>
  8. <asp:ListItem Value="5">Pune</asp:ListItem>
  9. <asp:ListItem Value="6">Banglore</asp:ListItem>
  10. <asp:ListItem Value="7">Lucknow</asp:ListItem>
  11. </asp:ListBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="lstboxCity" InitialValue="" runat="server" ErrorMessage="Please select atleast one city"></asp:RequiredFieldValidator>
  12. </div>
  13. <br />
  14. <div>
  15. <asp:DropDownList ID="ddlCity" runat="server" Width="200px">
  16. <asp:ListItem Value="0">--Select--</asp:ListItem>
  17. <asp:ListItem Value="1">Delhi</asp:ListItem>
  18. <asp:ListItem Value="2">Noida</asp:ListItem>
  19. <asp:ListItem Value="3">Gurgaon</asp:ListItem>
  20. <asp:ListItem Value="4">Mumbai</asp:ListItem>
  21. <asp:ListItem Value="5">Pune</asp:ListItem>
  22. <asp:ListItem Value="6">Banglore</asp:ListItem>
  23. <asp:ListItem Value="7">Lucknow</asp:ListItem>
  24. </asp:DropDownList>
  25. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="ddlCity" InitialValue="0" runat="server" ErrorMessage="Please select city"></asp:RequiredFieldValidator>
  26. </div>
  27. <br />
  28. <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
  29. </form>



Note

For validating DropDown List, make sure you have "--Select--" option value 0 other wise validation on it will not work.
Summary
In this article I try to explain how to validate DropDownList and ListBox using Required Field Validator. I hope after reading this article you will be able to use this trick in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.