我在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