PHP邮件表单错误时无法验证

时间:2015-07-26 14:51:07

标签: php validation

最近我在我的网站上添加了一个PHP邮件表单,用户可以在那里发送电子邮件并收到它们。然而,由于一个奇怪的原因,错误消息不会显示在用户屏幕上。

例如,如果用户将字段留空并单击“提交”,则会发送电子邮件而不会给出错误,并说明该字段是必需的。

这里是验证器的PHP代码:

<?php
define("EMAIL", "ITSPRIVATE@outlook.com");

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

  include('validate.class.php');

  //assign post data to variables
  $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $message = trim($_POST['message']);

  //start validating our form
  $v = new validate();
  $v->validateStr($name, "name", 3, 75);
  $v->validateEmail($email, "email");
  $v->validateStr($message, "message", 5, 1000); 

  if(!$v->hasErrors()) {
        $header = "From: $email\n" . "Reply-To: $email\n";
        $subject = "Contact Form Subject";
        $email_to = EMAIL;

        $emailMessage = "Name: " . $name . "\n";   
        $emailMessage .= "Email: " . $email . "\n\n";
        $emailMessage .= $message;

    //use php's mail function to send the email
        @mail($email_to, $subject ,$emailMessage ,$header ); 

    //grab the current url, append ?sent=yes to it and then redirect to that url
        $url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        header('Location: '.$url."?sent=yes");

    } else {
    //set the number of errors message
    $message_text = $v->errorNumMessage();      

    //store the errors list in a variable
    $errors = $v->displayErrors();

    //get the individual error messages
    $nameErr = $v->getError("name");
    $emailErr = $v->getError("email");
    $messageErr = $v->getError("message");
  }//end error check
}// end isset
?>

<?php



<div id="mainbox">
<div id="contact_form_wrap">
    <span class="message"><?php echo $message_text; ?></span>
    <?php echo $errors; ?>
    <?php if(isset($_GET['sent'])): ?><h2>Your message has been sent</h2><?php endif; ?>
    <form id="contact_form" method="post" action=".">
      <p><label>Name:<br />
      <input type="text" name="name" class="textfield" value="<?php echo htmlentities($name); ?>" />
      </label><br /><span class="errors"><?php echo $nameErr; ?></span></p>

      <p><label>Email: <br />
      <input type="text" name="email" class="textfield" value="<?php echo htmlentities($email); ?>" />
      </label><br /><span class="errors"><?php echo $emailErr ?></span></p>         

      <p><label>Message: <br />
      <textarea name="message" class="textarea" cols="45" rows="5"><?php echo htmlentities($message); ?></textarea>
      </label><br /><span class="errors"><?php echo $messageErr ?></span></p>

      <p><input type="submit" name="submit" class="button" value="Submit" /></p>
    </form>
  </div>
</div>

这是validate.class.php的代码。

<?php
class validate {

  // ---------------------------------------------------------------------------
  //  paramaters
  // ---------------------------------------------------------------------------

  /**
  * Array to hold the errors
  *
  * @access public
  * @var array
  */
  public $errors = array();

  // ---------------------------------------------------------------------------
  //  validation methods
  // ---------------------------------------------------------------------------

  /**
  * Validates a string
  *
  * @access public
  * @param $postVal - the value of the $_POST request
  * @param $postName - the name of the form element being validated
  * @param $min - minimum string length
  * @param $max - maximum string length
  * @return void
  */
  public function validateStr($postVal, $postName, $min = 5, $max = 500) {
    if(strlen($postVal) < intval($min)) {
      $this->setError($postName, ucfirst($postName)." must be at least {$min} characters long.");
    } else if(strlen($postVal) > intval($max)) {
      $this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
    }
  }// end validateStr

  /**
  * Validates an email address
  *
  * @access public
  * @param $emailVal - the value of the $_POST request
  * @param $emailName - the name of the email form element being validated
  * @return void
  */
  public function validateEmail($emailVal, $emailName) {
    if(strlen($emailVal) <= 0) {
      $this->setError($emailName, "Please enter an Email Address");
    } else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
      $this->setError($emailName, "Please enter a Valid Email Address");
        }
  }// end validateEmail

  // ---------------------------------------------------------------------------
  //  error handling methods
  // ---------------------------------------------------------------------------

  /**
  * sets an error message for a form element
  *
  * @access private
  * @param string $element - name of the form element
  * @param string $message - error message to be displayed
  * @return void
  */
  private function setError($element, $message) {
    $this->errors[$element] = $message;
  }// end logError

  /**
  * returns the error of a single form element
  *
  * @access public
  * @param string $elementName - name of the form element
  * @return string
  */
  public function getError($elementName) {
    if($this->errors[$elementName]) {
      return $this->errors[$elementName];
    } else {
      return false;
    }
  }// end getError

  /**
  * displays the errors as an html un-ordered list
  *
  * @access public
  * @return string: A html list of the forms errors
  */
  public function displayErrors() {
    $errorsList = "<ul class=\"errors\">\n";
    foreach($this->errors as $value) {
      $errorsList .= "<li>". $value . "</li>\n";
    }
    $errorsList .= "</ul>\n";
    return $errorsList;
  }// end displayErrors

  /**
  * returns whether the form has errors
  *
  * @access public
  * @return boolean
  */
  public function hasErrors() {
    if(count($this->errors) > 0) {
      return true;
    } else {
      return false;
    }
  }// end hasErrors

  /**
  * returns a string stating how many errors there were
  *
  * @access public
  * @return void
  */
  public function errorNumMessage() {
    if(count($this->errors) > 1) {
            $message = "There were " . count($this->errors) . " errors sending your message!\n";
        } else {
            $message = "There was an error sending your message!\n";
        }
    return $message;
  }// end hasErrors

}// end class

感谢您就如何解决这个问题提出建议。

1 个答案:

答案 0 :(得分:1)

验证位按预期工作;这是你的表格action导致它不会被激发。

取出action="."

所以

<form id="contact_form" method="post">

将在同一页面上显示表单。

您可以在此处看到验证工作正常,http://ideone.com/KV9CLX

同样如此指出

<?php



<div id="mainbox">

会导致错误,但可能是您的实际代码中没有错误,或者您没有任何输出..