Using a RequiredFieldValidator on a DropDownList in ASP .NET

Using a RequiredFieldValidator on a DropDownList in ASP .NET

In most applications today drop-down lists default to a “Please select..” option with some form of validation to ensure the user makes their own selection.

Drop-down list validation example

In ASP .NET web forms this frequently results in a drop-down list being created using code similar to that displayed below.

<asp:DropDownList ID="ddlOptions" AppendDataBoundItems="true" runat="server">
    <asp:ListItem Text="Please select an option..." Value="-1" />
</asp:DropDownList>

We can add an ASP .NET RequiredFieldValidator and set its ControlToValidate property to the ID of the DropDownList control as shown below.

<asp:RequiredFieldValidator ErrorMessage="You must select an option." ControlToValidate="ddlOptions"runat="server" />

This code would result in the drop-down list always passing validation since theRequiredFieldValidator sees the default value of “-1” as a valid value.

To correct this we need to set the InitialValue property of the RequiredFieldValidator to be the same as the initial value of the DropDownList (in this case “-1′) as shown below.

<asp:RequiredFieldValidator ErrorMessage="You must select an option." ControlToValidate="ddlOptions" InitialValue="-1" runat="server" />

After this property has been set the DropDownList control will not pass validation until the user has selected a different option.