PDA

View Full Version : mutlitple checkbox validation



vineet
10-03-2008, 02:19 PM
hi all

i have one form in which i have multiple checkbox options for the user to select.
i have inserted the validation script in this form which alert the user if the user has not selected any of the checkbox options. if one checkbox is selected then the form will get submit.

now i want that user should select atleast 4 checkboxes. plz help me with what to change or add in this script.

the form and javascript validation code is below :


<html>
<head>
<script language="javascript">

function validate()
{
var chks = document.getElementsByName('colors[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}

if (hasChecked == false)
{
alert("Please select at least one.");
return false;
}

return true;
}
</script>

</head>
<body>
<form name="form1" onSubmit="return validate()">

Your colors are <br>
<input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br>
<input type="checkbox" name="colors[]" value="red" id="red">red <br>
<input type="checkbox" name="colors[]" value="green" id="green">green <br>
<input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
<input type="checkbox" name="colors[]" value="voilet" id="voilet">voilet <br>
<input type="checkbox" name="colors[]" value="grey" id="grey">grey <br>

<br>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>

jscheuer1
10-03-2008, 04:29 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Check Four - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
if (c < 4) alert('Please select at least four.');
return c > 3;
};
</script>

</head>
<body>
<form action="#" name="form1" onsubmit="return validate(this)">
<div>
Your colors are <br>
<input type="checkbox" name="colors[1]" value="blue" id="blue">Blue <br>
<input type="checkbox" name="colors[2]" value="red" id="red">red <br>
<input type="checkbox" name="colors[3]" value="green" id="green">green <br>
<input type="checkbox" name="colors[4]" value="yellow" id="yellow">yellow <br>
<input type="checkbox" name="colors[5]" value="violet" id="violet">violet <br>
<input type="checkbox" name="colors[6]" value="gray" id="gray">gray <br>
<br>
<input type="submit" value="submit">
</div>
</form>
</body>
</html>

I changed the form and markup so that it would validate. I changed the color input's names to unique values so that in an ordinary server-side situation the individual colors chosen could be retrieved with ordinary GET or POST retrieval methods.

vineet
10-04-2008, 04:52 AM
hi john

thanks for the reply. your code when tested works fine when run only for javascript.
but when i inserted in my php form it doesnt works fine.
If you know php then should i insert the php code here for you to see whats wrong.

plz reply

vineet

jscheuer1
10-04-2008, 07:44 AM
I have some limited PHP knowledge. Go ahead and post it. I did say that I changed the names of the color inputs. This is required so that you can GET or POST the data in PHP or other server side code. But it also means that the values you are looking for in the receiving page or process will have these new names. Instead of colors[]=whatever, you will have:


colors[1]=blue
colors[2]=red
colors[3]=green
colors[4]=yellow
colors[5]=violet
colors[6]=gray

Also, I corrected 'grey' and 'voilet' which you had misspelled.

vineet
10-04-2008, 08:03 AM
I have some limited PHP knowledge. Go ahead and post it. I did say that I changed the names of the color inputs. This is required so that you can GET or POST the data in PHP or other server side code. But it also means that the values you are looking for in the receiving page or process will have these new names. Instead of colors[]=whatever, you will have:


colors[1]=blue
colors[2]=red
colors[3]=green
colors[4]=yellow
colors[5]=violet
colors[6]=gray

Also, I corrected 'grey' and 'voilet' which you had misspelled.
hi john

The php form and the javascript provided by you is inserted below. please review.

when i select colors[3][4][5][6], then the result displayed is color green. other 3 colors are not displayed.


<?php
if(isset($_REQUEST['submit']))
{
$user = $_REQUEST['fname'];
$age=$_REQUEST['age'];
$city=$_REQUEST['city'];
$gender=$_REQUEST['gender'];

$colors= array();
$colors=$_REQUEST['colors'];
for($i=0;$i<count($colors);$i++)
{
$selected_colors=$selected_colors . $colors[$i] . " , ";
}

echo "Hi = " . $user . "<br>";
echo "Your age is = " . $age. "<br>";
echo "You Live At = " . $city . "<br>";
echo "Your colors are = " . $selected_colors . "<br>";
echo "You are " . $gender;
}
else
{
?>

<html>
<head>
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
if (c < 4) alert('Please select at least four.');
return c > 3;
};
</script>


</head>
<body>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onSubmit="return

validate(this)">
Name : <input type="text" name="fname" />
<br>
Age :
<input type="text" name="age" />
<br>
<br>Choose city :
<select name="city">
<option>select city</option>
<option value="Chandigarh">Chandigarh</option>
<option value="calcutta">Calcutta</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
</select><br>

Your colors are <br>
<input type="checkbox" name="colors[1]" value="blue" id="blue">Blue <br>
<input type="checkbox" name="colors[2]" value="red" id="red">red <br>
<input type="checkbox" name="colors[3]" value="green" id="green">green <br>
<input type="checkbox" name="colors[4]" value="yellow" id="yellow">yellow <br>
<input type="checkbox" name="colors[5]" value="voilet" id="voilet">voilet <br>
<input type="checkbox" name="colors[6]" value="grey" id="grey">grey <br>

Gender<input type="radio" name="gender" value="male">Male <input type="radio" name="gender"

value="Female">Female
<br>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
<?php
}
?>

jscheuer1
10-04-2008, 08:25 AM
I did say that my PHP knowledge was limited. I wasn't aware that a $_REQUEST could be done as an array in the manner your PHP code seems to indicate. If that is the case, and your PHP code was working before, it should be fine to change it back to colors[] for all the color checkboxes. This will also require a slight change in the javascript code:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Check Four - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
if (c < 4) alert('Please select at least four.');
return c > 3;
};
</script>

</head>
<body>
<form action="#" name="form1" onsubmit="return validate(this)">
<div>
Your colors are <br>
<input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br>
<input type="checkbox" name="colors[]" value="red" id="red">red <br>
<input type="checkbox" name="colors[]" value="green" id="green">green <br>
<input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
<input type="checkbox" name="colors[]" value="violet" id="violet">violet <br>
<input type="checkbox" name="colors[]" value="gray" id="gray">gray <br>
<br>
<input type="submit" value="submit" name="submit">
</div>
</form>
</body>
</html>

vineet
10-05-2008, 05:13 AM
hi john

thanks very much your code works great.

tell me one thing that i have to validate 3 more fields (fname,age,city). i have the below validation

created for them.

if(document.form1.fname.value == '')
{
alert("enter name");
return false;
}

if(document.form1.age.value == '')
{
alert("enter age");
return false;
}

if(document.form1.city.value == '')
{
alert("enter city");
return false;
}

where should i put this code in your provided function. actually u have mentioned function name as

function validate(f). i think because of that (f) my other validation code is not working. please clarify

me how to do.

thanks
vineet


<?php
if(isset($_REQUEST['submit']))
{
$user = $_REQUEST['fname'];
$age=$_REQUEST['age'];
$city=$_REQUEST['city'];
$gender=$_REQUEST['gender'];

$colors= array();
$colors=$_REQUEST['colors'];
for($i=0;$i<count($colors);$i++)
{
$selected_colors=$selected_colors . $colors[$i] . " , ";
}

echo "Hi = " . $user . "<br>";
echo "Your age is = " . $age. "<br>";
echo "You Live At = " . $city . "<br>";
echo "Your colors are = " . $selected_colors . "<br>";
echo "You are " . $gender;
}
else
{
?>

<html>
<head>
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
if (c < 4) alert('Please select at least four.');
return c > 3;
}
</script>


</head>
<body>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onSubmit="return

validate(this)">
Name : <input type="text" name="fname" />
<br>
Age :
<input type="text" name="age" />
<br>
<br>Choose city :
<select name="city">
<option>select city</option>
<option value="Chandigarh">Chandigarh</option>
<option value="calcutta">Calcutta</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
</select><br>

Your colors are <br>
<input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br>
<input type="checkbox" name="colors[]" value="red" id="red">red <br>
<input type="checkbox" name="colors[]" value="green" id="green">green <br>
<input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
<input type="checkbox" name="colors[]" value="voilet" id="voilet">voilet <br>
<input type="checkbox" name="colors[]" value="grey" id="grey">grey <br>

Gender<input type="radio" name="gender" value="male">Male <input type="radio" name="gender"

value="Female">Female
<br>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
<?php
}
?>

jscheuer1
10-05-2008, 06:29 AM
function validate(f){
f = f.elements;
var msg = '', colors = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
if (c < 4) msg = '\nPlease select at least four colors.';
return c > 3;
}, valid = colors();
if(f['city'].options.selectedIndex == 0){
valid = false;
msg = '\nPlease enter City.' + msg;
};
if(f['age'].value == ''){
valid = false;
msg = '\nPlease enter Age.' + msg;
};
if(f['fname'].value == ''){
valid = false;
msg = '\nPlease enter Name.' + msg;
};
if(!valid) alert(msg.replace(/^\n/, ''));
return valid;
};

vineet
10-05-2008, 07:24 AM
hi john

all your code worked great.

i inserted one field [gender] which has two radio buton options male and female. one option is to be selected. the validation applied is

if(f['gender[0]'].checked == false) || (f['gender[1]'].checked == false){
valid = false;
msg = '\nPlease enter gender.' + msg;
};

why is it not working. if i comment the gender field validation then everything works fine.

vineet

<?php
if(isset($_REQUEST['submit']))
{
$user = $_REQUEST['fname'];
$age=$_REQUEST['age'];
$city=$_REQUEST['city'];
$gender=$_REQUEST['gender'];

$colors= array();
$colors=$_REQUEST['colors'];
for($i=0;$i<count($colors);$i++)
{
$selected_colors=$selected_colors . $colors[$i] . " , ";
}

echo "Hi = " . $user . "<br>";
echo "Your age is = " . $age. "<br>";
echo "You Live At = " . $city . "<br>";
echo "Your colors are = " . $selected_colors . "<br>";
echo "You are " . $gender;
}
else
{
?>

<html>
<head>
<script type="text/javascript">

function validate(f){
f = f.elements;
var msg = '', colors = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
if (c < 4) msg = '\nPlease select at least four colors.';
return c > 3;
}, valid = colors();
if(f['city'].options.selectedIndex == 0){
valid = false;
msg = '\nPlease enter City.' + msg;
};
if(f['age'].value == ''){
valid = false;
msg = '\nPlease enter Age.' + msg;
};
if(f['fname'].value == ''){
valid = false;
msg = '\nPlease enter Name.' + msg;
};

if(f['gender[0]'].checked == false) || (f['gender[1]'].checked == false){
valid = false;
msg = '\nPlease enter gender.' + msg;
};

if(!valid) alert(msg.replace(/^\n/, ''));
return valid;
};
</script>


</head>
<body>
<form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onSubmit="return validate(this)">
Name : <input type="text" name="fname" />
<br>
Age :
<input type="text" name="age" />
<br>
<br>Choose city :
<select name="city">
<option>select city</option>
<option value="Chandigarh">Chandigarh</option>
<option value="calcutta">Calcutta</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
</select><br>

Your colors are <br>
<input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br>
<input type="checkbox" name="colors[]" value="red" id="red">red <br>
<input type="checkbox" name="colors[]" value="green" id="green">green <br>
<input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
<input type="checkbox" name="colors[]" value="voilet" id="voilet">voilet <br>
<input type="checkbox" name="colors[]" value="grey" id="grey">grey <br>

Gender<input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="Female">Female
<br>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
<?php
}
?>

jscheuer1
10-05-2008, 09:20 AM
You are using || (logical OR). With a pair of radio buttons, one will always be false, and there is no gender[0] or gender[1]. In javascript, names are literal. Even in PHP, with radio button groups, only the value of the checked radio button is passed, that's why they can all have the same name with no []. Unfortunately, when checking the value in javascript, all radios must be evaluated individually (I do this in a loop). In an unrelated matter I just realized that since I changed all the color input names to 'colors[]', that makes their validation a little simpler. But since they no longer occupy the last position in the form, there are other changes to their validation as well.

However, at least in the US, it is generally illegal to require a person to disclose his/her gender unless it is needed, like if you are selling clothing, for male or female styles or sizing. But in a case like that, it should be worded as a preference, not as a declaration of gender, for example:


Male or Female sizes?
<br>
<input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="Female">Female

You can always ask a person's gender though, it just cannot be required for submission, and therefore should not be validated unless it is a preference, rather than a declaration.

In any case, here's how to validate those two radio buttons using our function (changes and additions, including ones for colors validation, highlighted):


function validate(f){
f = f.elements;
var msg = '', gender = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && f[i].name == 'gender' && f[i].checked)
return true;
msg = '\nPlease Check for Male or Female Sizes.';
return false;
}, valid = gender(), colors = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && f[i].name == 'colors[]' && f[i].checked) ++c;
if (c < 4) msg = '\nPlease Select at least Four Colors.' + msg;
return c > 3;
};
valid = colors()? valid : false;
if(f['city'].options.selectedIndex == 0){
valid = false;
msg = '\nPlease enter City.' + msg;
};
if(f['age'].value == ''){
valid = false;
msg = '\nPlease enter Age.' + msg;
};
if(f['fname'].value == ''){
valid = false;
msg = '\nPlease enter Name.' + msg;
};
if(!valid) alert(msg.replace(/^\n/, ''));
return valid;
};

vineet
10-05-2008, 09:56 AM
hi john

thanks.
it was really very nice the way you helped and explained me. i really appreciate it.
With the help of loops function i m not limited to the options for any field of the form. the code becomes smaller but would validate more options.

vineet


You are using || (logical OR). With a pair of radio buttons, one will always be false, and there is no gender[0] or gender[1]. In javascript, names are literal. Even in PHP, with radio button groups, only the value of the checked radio button is passed, that's why they can all have the same name with no []. Unfortunately, when checking the value in javascript, all radios must be evaluated individually (I do this in a loop). In an unrelated matter I just realized that since I changed all the color input names to 'colors[]', that makes their validation a little simpler. But since they no longer occupy the last position in the form, there are other changes to their validation as well.

However, at least in the US, it is generally illegal to require a person to disclose his/her gender unless it is needed, like if you are selling clothing, for male or female styles or sizing. But in a case like that, it should be worded as a preference, not as a declaration of gender, for example:


Male or Female sizes?
<br>
<input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="Female">Female

You can always ask a person's gender though, it just cannot be required for submission, and therefore should not be validated unless it is a preference, rather than a declaration.

In any case, here's how to validate those two radio buttons using our function (changes and additions, including ones for colors validation, highlighted):


function validate(f){
f = f.elements;
var msg = '', gender = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && f[i].name == 'gender' && f[i].checked)
return true;
msg = '\nPlease Check for Male or Female Sizes.';
return false;
}, valid = gender(), colors = function(){
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && f[i].name == 'colors[]' && f[i].checked) ++c;
if (c < 4) msg = '\nPlease Select at least Four Colors.' + msg;
return c > 3;
};
valid = colors()? valid : false;
if(f['city'].options.selectedIndex == 0){
valid = false;
msg = '\nPlease enter City.' + msg;
};
if(f['age'].value == ''){
valid = false;
msg = '\nPlease enter Age.' + msg;
};
if(f['fname'].value == ''){
valid = false;
msg = '\nPlease enter Name.' + msg;
};
if(!valid) alert(msg.replace(/^\n/, ''));
return valid;
};

jscheuer1
10-05-2008, 03:46 PM
Here's an even more compact way to do it, also slightly more efficient, perhaps easier to follow because it goes in the same order as the form:


function validate(f){
f = f.elements; var valid = true, msg = '';
if(f['fname'].value == '') valid = false, msg += 'Please Enter Name.';
if(f['age'].value == '') valid = false, msg += '\nPlease Enter Age.';
if(f['city'].options.selectedIndex == 0) valid = false, msg += '\nPlease Select City.';
for (var c = 0, g = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && f[i].name == 'colors[]' && f[i].checked) ++c;
else if (f[i].name && f[i].name == 'gender' && f[i].checked) ++g;
if (c < 4) valid = false, msg += '\nPlease Check at least Four Colors.';
if (g < 1) valid = false, msg += '\nPlease Check for Male or Female Sizes.';
if(!valid) alert(msg.replace(/^\n/, ''));
return valid;
};

kodelajagdish
07-24-2009, 05:06 AM
Thanks a lot ...