我的表单中有两个复选框:
<div class="label-input-wrapper pickup">
<div class="form-label">I need Airport pick-up</div>
<div class="form-input">
<input type="checkbox" name="pick_up" value="Yes" />Yes
<input type="checkbox" name="pick_up" value="No" />No
<div class="error-msg">
<?php if(isset($errors['pick_up_no'])) { echo '<span style="color: red">'.$errors['pick_up_no'].'</span>'; } ?>
</div>
</div>
</div>
保存上述复选框值的变量:$pickup = $_POST['pick_up'];
验证:
//Check the airport pickup and make sure that it isn't a blank/empty string.
if ($pickup == ""){
//Blank string, add error to $errors array.
$errors['pick_up_no'] = "Please let us know your airport pick up requirement!";
}
if (($pick_up = Yes) && ($pick_up = No)) {
//if both selected, add error to $errors array.
$errors['pick_up_no'] = "Can not select Yes and No together!";
}
但上述验证只是打印Can not select Yes and No together!
,如果两者都未被选中,或者只选择了一个,或者两者都被选中。它为所有选择提供相同的错误消息。为什么呢?
答案 0 :(得分:3)
您目前正在使用单个=
符号进行分配,而不是将==
与
if (($pick_up = Yes) && ($pick_up = No))
您需要将其更改为
if (($pick_up == "Yes") && ($pick_up == "No")){...}
将Yes
和No
括在引号内,以便将其视为字符串。
<强> 编辑: 强>
你最好的选择是使用单选按钮,恕我直言。
使用复选框时,不应使用“是”和“否”选项;这令人困惑。
它应该是Yes
或 No
而不是 和 。
<input type="radio" name="pick_up" value="Yes" />Yes
<input type="radio" name="pick_up" value="No" />No
这是最可行的解决方案。
答案 1 :(得分:2)
我不知道为什么你需要一个复选框(这是单选按钮应该做的),但你可以这样做:
if(!isset($_POST['pick_up']) || count($_POST['pick_up']) > 1) {
echo 'please select at least 1 choice';
} else {
echo $_POST['pick_up'][0];
}
然后设置您的复选框名称:
name="pick_up[]"
或者,如果您确实需要单独的错误消息。做这样的事情:
$errors['pick_up_no'] = '';
if(!isset($_POST['pick_up'])) {
$errors['pick_up_no'] = "Please let us know your airport pick up requirement!";
} elseif(count($_POST['pick_up']) > 1) {
$errors['pick_up_no'] = "Can not select Yes and No together!"; // weird UX, should have prevented this with a radio button
}
if($errors['pick_up_no'] != '') {
echo $errors['pick_up_no'];
} else {
echo $_POST['pick_up'][0];
}
答案 2 :(得分:1)
$ _POST ['pick_up']不可能同时为yes和no,因为名称是pick_up而不是pick_up []&lt; - 指向多个变量。因此,无论哪种方式都是“是”或“否”,因为一个参数将覆盖另一个参数。在这种情况下,你必须使用javascript来验证在提交之前只检查了一个。
答案 3 :(得分:1)
使用复选框字段元素数组;
<input type="checkbox" name="pick_up[]" />Yes
<input type="checkbox" name="pick_up[]" />No
然后在你的PHP脚本中:
<?php
$pick_ups=$_POST['pick_up'];
$first=isset($pick_ups[0]); //true/false of first checkbox status
$second=isset($pick_ups[1]); //true/false of second checkbox status
?>
同样,正如您已经被告知的那样,您应该使用单选按钮来达到此目的!考虑到没有设置$ _POST不发送复选框(使用isset检查($ _ POST [&#39; name&#39;])