Reputation: 33
Having issue in my server side validation in checkbox?Here I have listed three checkbox.it is mandatory user select any one checkbox.How to validate in server side using php.I have given mycode. I have written using OR condition.if all the checkbox is null.it shows error,I don't want this.my issue is user select any one in three checkbox.how to validate in server side? My Form:
<form name="vk" action="" method="post"/>
<?php
if($error!='')
{
?>
<div style="color:#FF0000;"><?php echo $error;?></div>
<?php
}
?>
</td>
</tr>
Name:<input type="name" name="username" value=""/><br/><br/>
password:<input type="password" name="password" value=""/><br/><br/>
Please select subject<input type="checkbox" name="allsubject" id="all" value="allsubject">All Subject
<input type="checkbox" name="science" value="science">Science
<input type="checkbox" name="maths" value="maths">Maths
<input type="submit" name="submit" value="Submit"/>
</form>
My php code:
<?php
if(isset($_POST['submit']))
{
$name=$_POST['username'];
$password=$_POST['password'];
$allsubject=$_POST['allsubject'];
$science=$_POST['science'];
$maths=$_POST['maths'];
$error='';
if($name=='')
{
$error.='name Id required.<br/>';
}
if($password=='')
{
$error.='Password required.<br/>';
}
if(empty($allsubject) || empty($science) || empty($maths))
{
$error.="You didn't select any subject.";
}
}
?>
Upvotes: 2
Views: 675
Reputation: 61
Firstly, name of checkboxes should same and their values differs:
Please select subject
<input type="checkbox" name="subject[]" id="all" value="all">All Subject
<input type="checkbox" name="subject[]" value="science">Science
<input type="checkbox" name="subject[]" value="maths">Maths
The corresponding php code would be
$subjectSelected = $_POST['subject'];
if(empty($subjectSelected) || (count($subjectSelected) < 1)) {
$error.='subject required.<br/>';
}
though second OR is not required in if condition, it would be good if you put it.
Upvotes: 1
Reputation: 81
The checkbox only used type Boolean values, means that only work using "true or false.
if($allsubject == true || $science == true || $maths == true)
{
$error.='subject required.<br/>';
}
Upvotes: 1