PHP - PHP中字段和消息的表单验证

时间:2016-03-12 20:28:25

标签: php forms validation

我想在将信息发送给我之前对其进行验证。例如,电子邮件地址上有一个@。

我有以下代码介绍:姓名,姓氏和电子邮件。我证实它们不是空的,但是:

  1. 如何向用户发送消息让他们知道他们需要填写消息?我尝试过:if($ nameErr ==''){echo"需要引入一个名字"}
  2. 但它确实无法运作

    1. 如何验证类型:确保电子邮件地址有@或电话是数字且有9位?
    2. 非常感谢

      <!DOCTYPE HTML>
      <html>
      <head>
      <style>
      .error {color: #FF0000;}
      </style>
      </head>
      <body>
      
      <?php
      // define variables and set to empty values
      $nameErr = $emailErr = $surnameErr = "";
      $name = $email = $surname = "";
      
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
         if (empty($_POST["name"])) {
           $nameErr = "Name is required";
         } else {
           $name = test_input($_POST["name"]);
         }
      
         if (empty($_POST["email"])) {
       $emailErr = "Email is required";
         } else {
       $email = test_input($_POST["email"]);
         }
      
         if (empty($_POST["surname"])) {
       $surname = "";
         } else {
       $surname = test_input($_POST["surname"]);
         }
      }
      
      function test_input($data) {
         $data = trim($data);
         $data = stripslashes($data);
         $data = htmlspecialchars($data);
         return $data;
      }
      ?>
      
      <h2>PHP Form Validation Example</h2>
      <p><span class="error">* required field.</span></p>
      <form method="post" action="<?php echo     htmlspecialchars($_SERVER["PHP_SELF"]);?>">
         Name: <input type="text" name="name">
         <span class="error">* <?php echo $nameErr;?></span>
         <br><br>
         Last Name: <input type="text" name="surname">
         <span class="error">*<?php echo $surnameErr;?></span>
         <br><br>
         E-mail: <input type="text" name="email">
         <span class="error">* <?php echo $emailErr;?></span>
         <br><br>
         <input type="submit" name="submit" value="Submit">
      </form>
      
      
      </body>
      </html>
      

1 个答案:

答案 0 :(得分:-1)

您实际上并不需要自己编写所有验证代码。如果您使用像http://respect.github.io/Validation/这样的库,则会更方便。