1. Home
  2. Computing & Technology
  3. JavaScript

Drop Down List Validation

clr gif
Join the Discussion

Questions? Comments?

Validation of dropdown lists is fairly simple. Since the only possible values that the list can have are the ones that you code into the list, the only invalid values will be ones that you knowingly put there.

Why would you put invalid values into a drop down list in the first place? Well often you want to make sure that the person filling out the form actually selects an option from the list and does not just get the top entry in the list by default so you make the top entry blank and consider that to be an invalid response.

A second reason for adding invalid entries to a list is to place separators between entries to divide them into groups.

Here is a sample drop down list that contains entries of both of these invalid types as well as several valid entries. If you change the selection then an alert box will tell you whether you have selected a valid or invalid entry.

So how do we validate the selected entry in the dropdown list? Well take a look at how the values have been assigned to the options in the drop down list. Here is the code with the value fields for the invalid entry fields shown in bold:

<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="">-----</option>
<option value="3">Three</option>

As you can see, the value fields for all of the invalid entries are set to an empty string. It is now a simple matter of testing whether the value field is empty or not to determine if the selection is valid. Here is the Javascript function that we use to test this:

function valDrop(val) {
if (val == '') return false;
else return true;
}

In your form validation you simply pass the value of the select field that contains your option list as a parameter to the valDrop() function and the function will return true if the option selected is valid and false if it is not.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.