RequiredFieldValidator not working for Dropdownlist

user3122107 picture user3122107 · Mar 4, 2014 · Viewed 7.4k times · Source

I have a Dropdownlist in my web page as follows.

<asp:DropDownList runat="server" ID="cboNoOfSubjects" AutoPostBack="true" CssClass="textEntry"  width="80%" onclick="javascript:shouldsubmit=false;" ValidationGroup="valCourseFees">
   <asp:ListItem Value="0">-Select-</asp:ListItem>
   <asp:ListItem Value="1">1</asp:ListItem>
   <asp:ListItem Value="2">2</asp:ListItem>
   <asp:ListItem Value="3">3</asp:ListItem>
   <asp:ListItem Value="4">4</asp:ListItem>
   <asp:ListItem Value="5">5</asp:ListItem>
</asp:DropDownList>
    <font color ="red">*</font> 

<asp:RequiredFieldValidator ID="cboNoOfSubjects_RequiredFieldValidator" 
 runat="server" ErrorMessage="No. of Subjects Required" ForeColor="Red"
 Font-Size="0.9em" ControlToValidate="cboNoOfSubjects" 
ValidationGroup="valCourseFees" Display="None"></asp:RequiredFieldValidator>

But the validator does not seem to fire. Can anyone help me with this?

Answer

MusicLovingIndianGirl picture MusicLovingIndianGirl · Mar 4, 2014

For all RequiredFieldValidators, the InitalValue property is important. Add it to yours and it will work.

<asp:RequiredFieldValidator ID="cboNoOfSubjects_RequiredFieldValidator" runat="server"  
 ErrorMessage="No. of Subjects Required" ForeColor="Red" InitialValue="0"
 Font-Size="0.9em" ControlToValidate="cboNoOfSubjects" 
 ValidationGroup="valCourseFees" Display="None"></asp:RequiredFieldValidator>

One thing more to change, you have to set the property Display="Dynamic" which will display accordingly.