【问题标题】:PHP - Single checkbox validation - validates but even when checked, won't submit. [closed]PHP - 单个复选框验证 - 验证但即使选中,也不会提交。 [关闭]
【发布时间】:2013-05-14 20:45:47
【问题描述】:

我正在为 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 是否未设置
  • ALL 标头位置之后添加 exit();。 (您可能还想在index.php 末尾取消设置$_SESSION['validerrors'],否则另一个页面也可能显示这些错误!)
  • 感谢您的帮助! @Waygood - 将所有内容添加到此页面和其他页面中,谢谢!

标签: php validation checkbox


【解决方案1】:

您正在调用此代码:

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 语句上方。

【讨论】:

  • 非常感谢!我现在感觉自己像个白痴!我会确保在 10 分钟后给出答案!
猜你喜欢
  • 1970-01-01
  • 2018-07-02
  • 2012-10-01
  • 2016-05-28
  • 1970-01-01
  • 2015-12-15
  • 2011-10-11
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多