Validating php multiple-value checkbox form element with javascript

In php a multiple-value form element such as checkbox is named suffixed with a set of square brackets. For example,

My commonly used colors are:

<form action="index.php" name="myform" method="post" onsubmit="return validate_form();">
<input type="checkbox" name="colors[]" value="red" />
<input type="checkbox" name="colors[]" value="green" />
<input type="checkbox" name="colors[]" value="blue" />

To validate these kind of checkboxes’ using javascript is little tricky. While on the other hand, having a single checkbox without multiple-value selection it would have been straight forward, something like this:

function validate_form()    {
// considering form element <input type="checkbox" name="color" value="red" />
if(true==document.myform.color.checked)    {
//checked, ok. Let it go.
}    else    {
//not checked, stop it.
}
}

Considering multiple-value selection the document.myform[].color.checked or document.myform[].color.length would throw javasript error. To make it work as expected the javascript code in your validate_form function will need some changes. Here we go.

function validate_form()    {
var flag = false; //at the initial state we assume that nothing is checked
for(var i=0; i < eval('document.myform.elements["colors[]"].length') ; i++)    {
if(true === eval('document.myform.elements["colors[]"]['+i+'].checked'))    {

flag=true; //at least some thing is checked, we are good to let them go past this check

/*
//Hint: As a separated implementation somewhere though, if you wanted you could trigger the checked/un-checked status of your checkbox like the following:
//document.myform.elements["colors[]"][i].checked = false; //or true etc.
*/
}
}

if(true==flag)    {
//checked (at least something), ok. Let it go.
//Hint: if you wanted that all your checkbox should have been checked check for the value of i variable
}    else    {
//not checked, stop it.
}
}

In line 3 of modified function above we use powerful eval function to evaluate the string passed to it. The eval function accepts any valid piece of javascript code and returns output value. In the passed code string to eval function we write normal (parent to child access) algorithm to access the elements property (and its element) of myform object which is a property of our web page (document) object.

One thought on “Validating php multiple-value checkbox form element with javascript

  1. I want to a code which check the validation of different fields.
    Here if i do not fill the first two then it is impossible to leave comment.
    Like this.

Leave a Reply