簡體   English   中英

php isset()函數無法進行表單驗證

[英]php isset() function not working on form validation

我已經進行了以下驗證,但對它的工作方式感到困惑。 我正在對每個字段進行標准的isset()檢查,我想為未設置的每個字段打印一條錯誤消息。 但是由於某種原因,它對我來說根本不起作用。

<?php 

  if (isset($_POST["submit"])) {

    //show hr on click
    $error_design = "<hr> <p id='error_msg'>Please Fix Below Errors: <p>";


    $user_name = $_POST["name"];
    $user_email = $_POST["email"];
    $user_age = $_POST["age"];

    $validation_errors = " ";
    $error_counter = null;

    if (isset($_POST["name"])) {
      $validation_errors .= "<li class='validation_errors'>Please input your name.</li>";
      $error_counter++;
    }

    if (isset($user_email)) {
      $validation_errors .= "<li class='validation_errors'>Please input your email.</li>";
      $error_counter++;
    }

    if (isset($user_age)) {
      $validation_errors .= "<li class='validation_errors'>Please input your age.</li>";
      $error_counter++;
    } elseif (intval($user_age) < 18) {
      $validation_errors .= "<li class='validation_errors'>You must be over 18 years old.</li>";
      $error_counter++;
    }


    if ($error_counter = null) {

      $validation_errors = "<li class='validation_success'>Message successfully sent!</li>";

    }

  }

?>


<!DOCTYPE html>
<html>
<head>

  <meta charset="utf-8">

  <title>SandBox</title>

  <link rel="stylesheet" type="text/css" href="css/style.css">
  <link rel="stylesheet" href="css/animate.css">

  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript" src="js/script.js"></script>
</head>
<body>

  <header>

  </header>

  <form action="" method="post">

    <div class="input_group">
      <label for="name">Name</label>
      <input type="text" name="name">
    </div>

    <div class="input_group">
      <label for="email">eMail</label>
      <input type="email" name="email">
    </div>

    <div class="input_group">
      <label for="age">Age</label>
      <input type="text" name="age">
    </div>

    <input type="submit" value="Send" name="submit" id="submit">

    <?php echo $error_design; ?>

    <div>

      <ul>

        <?php echo $validation_errors; ?>

      </ul>

    </div>

  </form>


  <footer></footer>

</body>
</html>

那是因為您在這里使用了錯誤的功能。

isset()檢查變量是否被設置並且不為null但是當您發送帶有空字段的表單時,您將得到空字符串。 在這種情況下, isset()將返回true

您必須使用empty()並僅檢查字符串長度以確保存在某些內容。

在您的情況下,您嘗試檢查變量是否未設置,但是在代碼中實際檢查變量是否已設置,因此將每個isset()替換為if(!isset())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM