如何处理和显示多个表单验证错误?

时间:2014-06-26 21:12:17

标签: php html forms

所以我有一个表格,需要验证它。所以我正在做的是

if(empty($name) || empty($username) || empty($email) || empty($password)){
    $_SESSION['comp_form'] = "Complete all fields";
    header('Location: register.php');
}
if(strlen($password) < 5){
    $_SESSION['pass_leng'] = "Choose a longer password";
    header('Location: register.php');
}

我这样做是因为我需要在另一个页面上显示Session,但只显示一个错误。我想要做的就是这样,所有错误都会立即出现。

enter image description here

我是否在正确的轨道上?或者还有另一种方法可以解决这个问题。因为我只能使用

一次显示一条消息
$_SESSION['comp_form'] = "Complete all fields";
header('Location: register.php');
exit() 

3 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

$_SESSION['error'] = 0;
if(empty($name) || empty($username) || empty($email) || empty($password)){
    $_SESSION['comp_form'] = "Complete all fields";
    $_SESSION['error'] = 1;
}
if(strlen($password) < 5){
    $_SESSION['pass_leng'] = "Choose a longer password";
    $_SESSION['error'] = 1;
}
if($_SESSION['error'] == 1){
    header('Location: register.php');
}

除非你想使用AJAX,否则会以使用JavaScript为代价来提高网站的流畅度。

答案 1 :(得分:2)

您可以在验证期间构建一系列错误,然后检查数组中是否存在错误,如果存在则重定向。您还可以使用数组键来标识要显示每个错误的字段。

以下是一个例子:

$errors = array();

if(empty($name) || empty($username) || empty($email) || empty($password)){
    $errors['comp_form'] = "Complete all fields";
}
if(strlen($password) < 5){
    $errors['pass_leng'] = "Choose a longer password";
}

// more validation here if you wish
if(count($errors) > 0) {
    $_SESSION['errors'] = $errors;
    header("Location: register.php");
    exit;
} else {
    // clean up previous validation errors, everything's fine
    unset($_SESSION['errors']);
}

然后在您的表单上,您可以检查错误:

<!-- add hasError class to input when validation failed to allow you to style it -->
<input type="password" name="password" class="<?php if(isset($_SESSION['errors']['pass_leng'])) echo 'hasError'; ?>">
<!-- if there's an error, output it on a generic error message element -->
<?php if(isset($_SESSION['errors']['pass_leng'])) echo '<p class="formError">' . $_SESSION['errors']['pass_leng'] . '</p>'; ?>

答案 2 :(得分:2)

创建一个需要验证的字段数组(与其$_POST名称匹配):

$fields = array(
  'name'     => 'Name', 
  'username' => 'Username',
  'email'    => 'E-Mail',
  'password' => 'Password'
);

然后循环遍历它们,如果它们无效,请将它们添加到$_SESSION['errors']数组:

$_SESSION['errors'] = array(); 

foreach ($fields as $field => $niceName) {
    if (empty($_POST[$field])) {
        $_SESSION['errors'][$field] = $niceName . ' cannot be empty';
    } elseif ($field == 'password' && strlen($_POST[$field]) < 5) {
       $_SESSION['errors'][$field] = 'Choose a longer password';
    }      
}

然后,如果$_SESSION['errors']不为空,则可以重定向:

if (!empty($_SESSION['errors'])) {
    header('Location: register.php');
    exit(); 
}