搜尋

首頁  >  問答  >  主體

遇到問題的表單驗證,請指出問題所在(PHP驗證)

我想知道在我的程式碼中表單出了什麼問題。

<?php

if(isset($_POST['submit'])) {
  $arrayName = array("TeacherA", "TeacherB", "TeacherC" , "TeacherD", "TeacherE");

  $minimum = 5;
  $maximum = 10;

  $name = $_POST['yourName'];
  $email = $_POST['yourEmail'];

  if(strlen($name) < $minimum) {
    echo "Your name should be longer than 5 characters";
  } 
  
  if(strlen($name) > $maximum) {
    echo "Your name should not be longer than 10 characters";
  } 
  
  if(!in_array($name,$arrayName)){
    echo "Please do register with us before you can login";
  } else {
    echo "Welcome!";
  }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blank</title>
</head>
<body>
  <form action="form.php" method="post">
    <label>Your Name:    </label>
    <input type="text" name="yourName"> <br>

    <label for="">Your E mail:</label>
    <input type="email" name="yourEmail" id=""><br>
    
    <!-- <textarea name="yourMessage" id="" cols="30" rows="10"></textarea><br> -->
    <input type="submit" name="submit" value="submit">
  </form>
</body>
</html>

我在本地運行了程式碼,但是無法得到我想要的結果。

我想要的結果是,如果我沒有在「Your Name」欄位中輸​​入姓名,那麼應該顯示結果:

請在登入前先註冊

P粉268284930P粉268284930493 天前569

全部回覆(1)我來回復

  • P粉232793765

    P粉2327937652023-09-10 13:59:13

    如果「Your Name」欄位為空,則其strlen($name)應為0,第一個if語句為真,並顯示Your name should be longer than 5 characters 你可以嘗試這個:

    <?php   
    if (isset($_POST['submit'])) {
        $arrayName = array("TeacherA", "TeacherB", "TeacherC", "TeacherD", "TeacherE");
        $minimum = 5;
        $maximum = 10;
        $name = $_POST['yourName'];
        $email = $_POST['yourEmail'];
        if (empty($name)) {
            echo "Please do register with us before you can login";
        } else {
            if (strlen($name) < $minimum) {
                echo "Your name should be longer than 5 characters";
            } else {
                if (strlen($name) > $maximum) {
                    echo "Your name should be less than 10 characters";
                } else {
                    if (in_array($name, $arrayName)) {
                        echo "Welcome!";
                    } else {
                        echo "Your login is not correct";
                    }
                }
            }
        }
    }
    ?>

    i used empty() to test if the field empty and i used if-else statements because i want the script to stop if it founds a 'true' condition in your script you can use return; but that will exit the rest of your script

    have a nice code :)

    回覆
    0
  • 取消回覆