复选框中的服务器端验证有问题吗?在这里我列出了三个复选框。它是强制性的用户选择任何一个复选框。如何使用php在服务器端进行验证。我给了霉素。我是用OR条件写的。如果所有复选框都为空。它显示错误,我不想要这个。我的问题是用户选择三分之一的复选框。如何在服务器端验证?我的表单:
<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>
我的php代码:
<?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.";
}
}
?>
复选框只使用类型布尔值,意味着只能使用"true或false"。
if($allsubject == true || $science == true || $maths == true)
{
$error.='subject required.<br/>';
}
首先,复选框的名称应该相同,但它们的值不同:
请选择主题
<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
相应的php代码将是
$subjectSelected = $_POST['subject'];
if(empty($subjectSelected) || (count($subjectSelected) < 1)) {
$error.='subject required.<br/>';
}
虽然if条件中不需要第二个OR,但如果你把它放进去就好了。