Today I wanted to talk about how to do client side validation on a multiselect form control in PHP environment. PHP handles the multiselect form control a little differently in the $_POST array. For this to be sent to the server side script and contain multiple elements, the control name must include brackets ( [ ] ).
This will make $_POST["foo"] and array, where you can then loop through the array object and handle the selected options. I recently ran into a problem with validation. I normally like to do both server side and client side validation on my form objects. I do client side validation just for the sake of client convenience. This will save a server call to find out that something is required or invalid. This is 'fake' security, since you cannot trust the client for proper validation, since they can turn off JavaScript, etc. So I always back up my validation with server side handling to ensure that data is clean.
<select name="foo[]" multiple="yes" size="5">
....
</select>
Now other languages do not need the brackets [] for multiselect form names for this to work, and I had trouble escaping the brackets within my JavaScript. Let's say the user must select at least one select option in the multiselect form control. Normally, I would create a JavaScript validation function similar to this:
<script language="JavaScript">
function validate(frm){
if(frm.foo.length == 0){
alert("Please select at least one category");
return false;
}
}
</script>
Now if I name the select control foo, the JavaScript would work, but the server side call would break, since this isn't an array. If I change the name to the proper foo[] and adjust my JavaScript to look at:
if(frm.foo[].length == 0){
or
if(frm.foo\[\].length == 0){
I will get the usually unknown object, because the browser is not recognizing the name. After getting some forum help, here is the proper method for JavaScript to recognize our bracketed form object name.
var fooArray = frm.elements['foo[]'];
var passVal = false;
for(i = 0; i < fooArray.length; i++){
if(fooArray[i].selected){
passVal = true;
break;
}
}
if(!passVal){
alert("You must select at least one category");
return false;
}
I hope this comes in handy for someone. Sometimes it's the worst spending time on simple concepts.
Go Back
