如何在不重新加载整个页面的情况下在php联系人表单中显示错误消息

时间:2019-05-10 17:03:20

标签: php

我正在创建一个联系表单,当用户没有正确编写电子邮件或将任何必需的表单留空时,我希望能够显示错误而无需重新加载整个页面。 这是我正在使用的代码 谢谢!

    <?php
      if(isset($_POST['submit'])){
        $name = htmlspecialchars(stripslashes(trim($_POST['name'])));
        $email = htmlspecialchars(stripslashes(trim($_POST['email'])));
        $message = htmlspecialchars(stripslashes(trim($_POST['message'])));
        if(!preg_match("/^[A-Za-z .'-]+$/", $name)){
          $name_error = 'Invalid name';
        }
        if(!preg_match("/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/", $email)){
          $email_error = 'Invalid email';
        }
        if(strlen($message) === 0){
          $message_error = 'Your message should not be empty';
        }
      }
    ?>

 <label for="name">Name:</label><br>
      <input type="text" name="name" class="form-control">
      <p><?php if(isset($name_error)) echo $name_error; ?></p>

 <label for="email">Email:</label><br>
      <input type="text" name="email" class="form-control">
      <p><?php if(isset($email_error)) echo $email_error; ?></p>

 <label for="message">Message:</label><br>
      <textarea name="message" class="form-control md-textarea"></textarea>
      <p><?php if(isset($message_error)) echo $message_error; ?></p>

<input type="submit" name="submit" value="Submit" class="btn btn-primary">
      <?php 
        if(isset($_POST['submit']) && !isset($name_error) && !isset($subject_error) && !isset($email_error) && !isset($message_error)){
          $to = 'ex@myemail.com'; // edit here
          $body = " Name: $name\n E-mail: $email\n Message:\n $message";
          if(mail($to, $subject, $body)){
            echo '<p style="color: green">Message sent</p>';
          }else{
            echo '<p>Error occurred, please try again later</p>';
          }
        }
    ?>  

0 个答案:

没有答案