Validating a Multiple Select in Javascript

The other day someone asked me how to validate a multiple select on a form in Javascript. They needed to check that the person filling out the form at least chose one option. This is what I came up with off of the top of my head.

Here is a basic multiple select.

<select id="color" multiple="multiple" size="5">
  <option>Red</option>
  <option>Orange</option>
  <option>Yellow</option>
  <option>Green</option>
  <option>Blue</option>
</select>

Here is the Javascript function code that you can pass a reference to a select to and it will return true if one or more options are chosen, otherwise it will return false.

function multiselect_validate(select) {
    var valid = false;
    for(var i = 0; i < select.options.length; i++) {
        if(select.options[i].selected) {
            valid = true;
            break;
        }
    }

    return valid;
}

Here is an example of how you could call the above function on a select.

// referencing the select above by id
multiselect_validate(document.getElementById('color'));

The example above is a little limited in that it will only ensure that at least one option is chosen. It wont work if you need to check that at least two (or more) options are selected. This modified function can take an additional argument to specify how many options need to be selected.

function multiselect_validate(select, num) {
    if(!num) {
        num = 1;
    }

    var valid = false;
    var found = 0;
    for(var i = 0; i < select.options.length; i++) {
        if(select.options[i].selected) {
            found++;
            if(found == num) {
                valid = true;
                break;
            }
        }
    }

    return valid;
}

Leave a Reply

{
}