I love the ASP.NET validation controls. There are times however when you need to know the ins-and-outs to use them successfully. For example, what do you do when you want to require an option to be selected from a DropDownList on the client side?
If you simply add a RequiredFieldValidator, set the right ValidationGroup and set the validator’s ControlToValidate property, when you submit the form the field will not be validated because you are missing a key piece of the puzzle. You need to set the validator’s InitialValue property for things to work.
Here is a working example:
<asp:DropDownList runat="server" ID="DropDownList1"> <asp:ListItem Value="0">Please select</asp:ListItem> <asp:ListItem Value="1">Option 1</asp:ListItem> <asp:ListItem Value="2">Option 2</asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator runat="server" ControlToValidate="DropDownList1" InitialValue="0"></asp:RequiredFieldValidator>
By setting the validator’s InitialValue to 0, we make sure that if nothing is selected from the DropDownList ie if value 0 is submitted, the validator marks the DropDownList control as invalid.