PHP - 单一复选框验证 - 验证但即使在选中时也不会提交。

时间:2013-05-14 12:36:53

标签: php validation checkbox

我在PHP中编写表单验证代码,但我遇到了复选框验证问题。 浏览表单时,如果不选中该复选框,则会显示正确的错误消息。

但是,即使您选中了复选框,它仍然会显示相同的错误消息。

以下是目前的代码:

if (isset($_POST['firstname'], $_POST['lastname'], $_POST['address'], $_POST['email'], $_POST['password'])) {
    $errors = array(); 

    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $address = $_POST['address'];
    $email = $_POST['email']; 
    $password = $_POST['password'];

    if (empty($firstname)) {
        $errors[] = 'First name can\'t be empty'; 
    }

    if (empty($lastname)) {
        $errors[] = 'Last name can\'t be empty'; 
    }

    if (empty($address)) {
        $errors[] = 'Address can\'t be empty';
    }

    if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
        $errors[] = 'Please enter a valid email'; 
    }

    if (empty($password)) {
        $errors[] = 'Password can\'t be empty'; 
    }

}

if (!isset($checkbox)) {
        $errors[] = 'Please agree to the privacy policy';
} 

$sex = $_POST['sex'];
$age = $_POST['age'];
$checkbox = $_POST['checkbox'];

$_SESSION['validerrors'] = $errors;
$_SESSION['firstname'] = $firstname;
$_SESSION['lastname'] = $lastname;
$_SESSION['address'] = $address;
$_SESSION['email'] = $email;
$_SESSION['sex'] = $sex;
$_SESSION['age'] = $age; 
$_SESSION['password'] = $password;
$_SESSION['checkbox'] = $checkbox;

if (!empty($errors)) {
    header('Location: index.php'); 
} else { 
    header('Location: writevalues.php'); 
}

上述代码中的其他所有内容都运行正常,但我无法找到任何有用的答案来验证复选框验证情况。提前致谢!

1 个答案:

答案 0 :(得分:5)

您正在调用此代码:

if (!isset($checkbox)) {
        $errors[] = 'Please agree to the privacy policy';
} 

在此之前:

$checkbox = $_POST['checkbox'];

所以当然isset($checkbox)会返回false,因为它没有在那时设置!

您可以将if语句更改为:

if(!isset($_POST['checkbox'])){ ...

或者将行$checkbox = $_POST['checkbox'];移到if语句之上。