如果为空字段则显示错误 - PHP

时间:2014-02-28 12:14:56

标签: php forms validation submit

如果任何字段为空,我想在同一页面上显示错误。

我已经有了这个,但是一旦页面被加载就显示空错误,而不是在提交空字段后出现。

<?php
    // Required field names
    $required = array('triangleSide1', 'triangleSide2', 'triangleSide3');

    // Loop over field names, make sure each one exists and is not empty
    $error = false;
    foreach($required as $field) 
    {
        if (empty($_POST[$field])) 
        {
            $error = true;
        }
    }

    if ($error) 
    {
        echo "ALL FIELDS ARE REQUIRED";
    } 
    else 
    {
        echo header('Location: formSuccess.php');
    }
?>

有什么想法吗? - 更新//我已经尝试了所有答案,到目前为止没有任何工作

4 个答案:

答案 0 :(得分:1)

将您在帖子中检查的所有内容包裹在此:

if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
    // Your code containing checks here
}

这样,它只会在使用POST请求时触发。

答案 1 :(得分:0)

如果您有输入,您将始终使用表单提交输入,例如隐藏的输入:

<input type='hidden' name='formsubmit' value='1'>


然后,您可以在验证其他输入之前对此进行测试

if($_POST["formsubmit"]) {
   // Required field names
    $required = array('triangleSide1', 'triangleSide2', 'triangleSide3');

    // Loop over field names, make sure each one exists and is not empty
    $error = false;
    foreach($required as $field) {
      if (empty($_POST[$field])) {
          $error = true;
        }
    }

    if ($error) {
        echo "ALL FIELDS ARE REQUIRED";
    } else {
        header('Location: formSuccess.php');
    }
}

此外,您不会回显header()

的返回

答案 2 :(得分:0)

OR another way ( I have something similar in one of my pages)
 function check_presence($value){
   return isset($value) && $value!=="";
 }
 function validate($required){
   global $error
   foreach($required as $field){
      $value = trim($_POST[$field]);
      if (!check_presence($value)){
          $error = true;          
      }
   }
   return $error;
}
then on the page containing the form and its validation code
$required = array('triangleSide1',  'triangleSide2', 'triangleSide3');
if(isset($_POST["submit"]){
   $error = validate($required);
   if ($error){
      echo "ALL FIELDS ARE REQUIRED";
   }
}

答案 3 :(得分:-1)

尝试isset instest of empty !!!

if (empty($_POST[$field]))

成为

if (isset($_POST[$field]))