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.
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;
}


December 30th, 2008 at 01:17:35
thanks very much…
i have used ur script in my website..
thanks.
July 30th, 2009 at 10:32:39
Can you show us how to ensure that ALL options are selected?
September 15th, 2009 at 20:42:53
In this example to ensure that all options are selected you could use the second function and your call would look like this:
multiselect_validate( document.getElementById('color'), document.getElementById('color').options.length );December 16th, 2009 at 04:49:04
thanks very much…
i have used ur script
January 22nd, 2010 at 16:35:22
how about when you have a color[] array ?
February 18th, 2010 at 23:41:02
thanks for good one