我在PHP中编写表单验证代码,但是我的复选框验证有问题。 当你浏览表单时,如果你没有选中复选框,它会给出正确的错误信息。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');
}
一切都在上面的代码中其他工作正常,但我一直没能找到任何有用的答案的复选框确认情况。提前致谢!所以当然
$checkbox = $_POST['checkbox'];
isset($checkbox)
是否会返回false
,因为它没有设置在这一点上:
你正在检查'$ checkbox'是否在你赋值之前没有设置 – billyonecan 2013-05-14 12:38:59
在__ALL__头位置后面加上'exit();'。 (你可能还想在'index.php'结尾处设置'$ _SESSION ['validerrors']',否则另一个页面可能会显示这些错误!) – Waygood 2013-05-14 12:43:20
感谢您的帮助! @Waygood - 在此页面和其他页面添加了所有内容,谢谢! – CMichael 2013-05-14 13:00:36