by

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.

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

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.

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