Validation of ListBox and DropDown List using Required Field Validator

Introduction

In asp.net there are some situations when a web developer needs to validate ListBox and DropDownList using Required Field Validator. It seems to be little bit tricky and also it avoids the use of JavaScript function to validate ListBox and DropDownList .
I am sharing the code which will help the Developers:


First for ListBox

<asp:ListBox ID="lstboxStudent" runat="server" Width="200px" SelectionMode="Multiple">

<asp:ListItem Value="1">Shrish</asp:ListItem>

<asp:ListItem Value="2">Saurabh</asp:ListItem>

<asp:ListItem Value="3">Seema</asp:ListItem>

<asp:ListItem Value="4">Maanas</asp:ListItem>

</asp:ListBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"ControlToValidate="lstboxStudent" InitialValue="" runat="server" ErrorMessage="Please select atleast one Student"></asp:RequiredFieldValidator>

And Now, For DropDownList

             <asp:DropDownList ID="ourCity" runat="server" Width="200px">

<asp:ListItem Value="0">--Select--</asp:ListItem>

<asp:ListItem Value="1">Capetown</asp:ListItem>

<asp:ListItem Value="2">NewYork</asp:ListItem>

<asp:ListItem Value="3">Sydeny</asp:ListItem>

<asp:ListItem Value="4">Mumbai</asp:ListItem>

</asp:DropDownList> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="ourCity" InitialValue="0" runat="server" ErrorMessage="Please select city"></asp:RequiredFieldValidator>