Thursday, December 13, 2012

Validate ListBox and DropDown List using Required Field Validator

In Asp.Net, sometimes we need to validate List Box and Drop Down List using Required Field validator. Here I am sharing the code for validating List Box and Drop Down List, it is tricky and avoids to use java script function for validation.

Validate ListBox

For validating List box using required field validator, you have to just set  InitialValue="" in your required field validator. It will validate List box if no item has beed selected in List box.

<div>

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

    <asp:ListItem Value="1">Asp.Net</asp:ListItem>

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

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

    <asp:ListItem Value="5">C++</asp:ListItem>

    <asp:ListItem Value="6">C#</asp:ListItem>

    <asp:ListItem Value="7">C</asp:ListItem>        

  </asp:ListBox>

  <asp:RequiredFieldValidator ID="ListboxRequiredFieldValidator" ControlToValidate
="lstboxProgramming" InitialValue="" runat="server" ErrorMessage="Please select atleast one technology!!"></asp:RequiredFieldValidator>     

</div>

<br />

<asp:Button ID="btnClcik" runat="server" Text="Click me!!" />

Validate Drop Down List

For validating Drop Down List using required field validator, you have to just set  InitialValue="0" in your required field validator. It will validate Drop Down List if selected value of Drop Down List will "0".

<div>

  <asp:DropDownList ID="drpProgramming" runat="server" Width="150px">

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

    <asp:ListItem Value="1">Asp.Net</asp:ListItem>

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

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

    <asp:ListItem Value="5">C++</asp:ListItem>

    <asp:ListItem Value="6">C#</asp:ListItem>

    <asp:ListItem Value="7">C</asp:ListItem>

  </asp:DropDownList>

  <asp:RequiredFieldValidator ID="ListboxRequiredFieldValidator" ControlToValidate
="drpProgramming" InitialValue="0" runat="server" ErrorMessage="Please select atleast one technology"></asp:RequiredFieldValidator>

</div>

<br />
<asp:Button ID="btnClcik" runat="server" Text="Click me!!" />
Note:- In drop down validation, if there is no item with value "0" in drop down list then required filed validator will not work.
Happy coding!!
kick it on DotNetKicks.com

No comments:

Post a Comment

^ Scroll to Top