我有php文件,不会验证显示正确的错误消息

时间:2018-03-30 10:24:52

标签: php

这不会在提交中显示错误消息,我不知道出了什么问题,我的代码对我来说似乎没问题。由于某种原因,span文件中的错误代码无法在文本失败时显示错误消息。在提交表格后,甚至没有回复出来的数据。

    <body>
        <form method="post" action="<?php echo
            $_SERVER['PHP_SELF']; ?>">
           <label>
              <input type="text" placeholder="Enter
              fullname here" name="name">
              <span class="err"><?php echo @$name_err; ?></span>
           </label>
           <label>
              <input type="text" placeholder="Enter 
               Email here" name="email">
               <span class="err"><?php echo @$email_err; ?></span>
               </label>
           <label>
               <input type="submit" value="submit">
            </label>
         </form>
      </body>
    </html>

     <?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {

        $name = $email = '';
        $name_err = $email_err = '';
        if(!empty($_POST['name'])) {
            $name = $_POST['name'];
       } else {
            $name_err = 'You fullname is required';
       }

        if(!empty($_POST['email'])) {
            $email = $_POST['email'];
       }else {
        $email_err = 'Your email is required';
    }
    }

   echo $name.'<br>';
   echo $email.'<br>';
?>

1 个答案:

答案 0 :(得分:1)

这应该有效。您应该在呈现表单之前检查错误。你也有错误的$ email_err变量名

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {

        $name = $email = '';
        $name_err = $email_err = '';
        if(!empty($_POST['name'])) {
            $name = $_POST['name'];
       } else {
            $name_err = 'You fullname is required';
       }

        if(!empty($_POST['email'])) {
            $email = $_POST['email'];
       }else {
        $email_err = 'Your email is required';
    }
    }

   echo $name.'<br>';
   echo $email.'<br>';
?>
<body>
    <form method="post" action="<?php echo
        $_SERVER['PHP_SELF']; ?>">
       <label>
          <input type="text" placeholder="Enter
          fullname here" name="name">
          <span class="err"><?php echo @$name_err; ?></span>
       </label>
       <label>
          <input type="text" placeholder="Enter 
           Email here" name="email">
           <span class="err"><?php echo @$email_err; ?></span>
           </label>
       <label>
           <input type="submit" value="submit">
        </label>
     </form>
  </body>
</html>