【问题标题】:PHP - Display error message inside text field if form fails validationPHP - 如果表单验证失败,则在文本字段内显示错误消息
【发布时间】:2014-05-13 13:27:49
【问题描述】:

您好,请原谅菜鸟的问题,因为我还在学习 PHP。我正在尝试进行基本的表单验证。我试图让验证时发现的任何错误在表单字段内以红色显示。如果没有发现错误,表单应该重定向到感谢页面。

我已经写了一个基本的验证,但我现在被困在如何正确地实现它上。

我的问题是:

  1. 如何在不发送表单的情况下让错误消息显示在表单字段中?
  2. 如果没有发现错误,我该如何发送表单?

我的代码如下:

HTML

<form id="enquire" method="post" action="thankyou.php">
        <h2>Test Drive an Audi Today</h2>
        <input type="text"  value="Name" class="textbox" id="name" name="name" onfocus="if(this.value=='Name') this.value='';" /><br />
        <br />
        <input type="text" value="Surname" class="textbox" id="surname" name="surname"  onfocus="if(this.value=='Surname') this.value='';"  /><br />
        <br />
        <input type="text" value="Contact Number" class="textbox" id="nr" name="nr" onfocus="if(this.value=='Contact Number') this.value='';"   /> <br />
        <br />
        <input type="text" value="Email" class="textbox" id="email" name="email"onfocus="if(this.value=='Email') this.value='';" /><br />
        <br />

    <select id="swapImg" name="model" class="modelSelect" onchange="swapImage()" >
       <option value="images/1.jpg">A4</option>
    <option value="images/2.jpg" selected="selected">A6</option>
    <option value="images/3.jpg">A8</option>
    </select>
        <br />
        <br />
          <input type="submit" name="submit" class="butt" value="Send"  />
           <span class="buttonText">We'll Call you Back!</span>
        </form> 

PHP

 if (isset($_POST['enquire'])){
              //condition
          $correct = false;

            //Get Info
        $name =  $_POST['name'];
        $surname = $_POST['surname'];
        $number = $_POST['nr'];
        $email = $_POST['email'];
        $_REQUEST['model'];

            //name fields 
            $string_exp = "/^[A-Za-z .'-]+$/";
            //email field
            $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

            //validate name field
            if($name == ""){
                $name_error="* Please enter your name";
                $correct = false;
            }

            else if (!preg_match($string_exp,$name)) {
            $name_error= "* Wrong Format";
            $correct= false;
            }

            //validate surname 
            if($surname == ""){
                $surname_error= "* Please enter your surname.";
                $correct= false;
            }
            else if(!preg_match($string_exp,$surname)){
                $surname_error= "* Wrong Format";
                $correct = false;
            }
            //check email
            if($email==""){
                $email_error="* Please enter your email";
                $correct = false;
            }
            else if(!preg_match($email_exp,$email)){
                $email_error = "* Wrong Format";
                $correct = false;
            }

            //check number
            if($number=""){
                $phone_error = "* Please enter your phone number";
                $correct = false;
            }
            else if(!is_numeric($number)){
            $phone_error ='* Please enter only numbers 0-9.';
            $correct = false;  
             }

             //proceed if all fields validate
        if($correct){
        $email_to  = "tim@yah.co";
        $subject ="New Enquiry";

            //set message 
      $email_message .= "First Name: ".($name)."\n";
      $email_message .= "Last Name: ".($lastname)."\n";
      $email_message .= "Email: ".($email)."\n";
      $email_message .= "Telephone: ".($telephone)."\n"; 
      $email_message .= "Model: ".($model)."\n";

       // create email headers
        $headers = 'From: '.$email."\r\n".
        'Reply-To: '.$email."\r\n" .
        @mail($email, $email_subject, $email_message, $headers);  

        header("thankyou.php");
        exit();

             }//end if
            }// end isset

如果有人能指出我正确的方向,将不胜感激。

【问题讨论】:

  • 如果您想在不发送表单的情况下验证表单,则需要使用 javascript。而且你必须在 PHP 中重新检查表单。
  • 记住... PHP 在服务器而不是客户端上运行,因此您必须使用 javascript。

标签: php forms validation


【解决方案1】:

您必须使用 javascript 来验证表单的输入。

如果要使用 PHP 验证,则应发出 AJAX 请求。

请参阅以下使用 jquery 的示例:

$('#enquire').submit(function(e){
  e.preventDefault()
  var $form = $(this);
  $.post(
    $form.attr('action'),
    $form.serialize(),
    function(data) {
      if (data.isError) {
        // do something with the error messages or other parameter
        console.log(data.errorMessages);
      } else {
        // make redirection
        document.location.href = "thankyou.php"
      }
    },
    'json'
  );
});

在您的 PHP 代码中,您必须像这样输出数据:

$errorMessages = array();

if($name == ""){
    $errorMessages[] = "* Please enter your name";
}

else if (!preg_match($string_exp,$name)) {
    $errorMessages[] = "* Wrong Format";
}

//validate surname 
if($surname == ""){
    $errorMessages[] = "* Please enter your surname.";
}
else if(!preg_match($string_exp,$surname)){
    $errorMessages[] = "* Wrong Format";
}

// after all validations return the results or continue registering the user
if (!empty($errorMessages)) {
    die(json_encode(array('isError' => true, 'errorMessages' => $errorMessages)));
}

// continue here the registration

【讨论】:

    【解决方案2】:

    这不是 php 问题。 PHP 是一种服务器端脚本工具,本质上意味着您需要将数据发送到服务器以供 PHP 使用。

    正如其他人所提到的,您最有可能最好使用 JavaSript 库 J-Query Validate 是一个非常常见且有用的方法,但可以肯定的是,还有许多其他方法。

    【讨论】:

    • 我把这个答案留在这里,但看起来 romulos 在我之前发布了一个非常相似的答案......
    【解决方案3】:

    要验证表单中的数据而不提交,您必须使用 javascript。 这是一个示例:

    <form id="enquire" method="post" action="thankyou.php">
        <div id='error-box' style='color:red;display:none'></div>
    
        <h2>Test Drive an Audi Today</h2>
        <input type="text"  value="Name" class="textbox" id="name" name="name" onfocus="if(this.value=='Name') this.value='';" /><br />
        <br />
        <input type="text" value="Surname" class="textbox" id="surname" name="surname"  onfocus="if(this.value=='Surname') this.value='';"  /><br />
        <br />
        <input type="text" value="Contact Number" class="textbox" id="nr" name="nr" onfocus="if(this.value=='Contact Number') this.value='';"   /> <br />
        <br />
        <input type="text" value="Email" class="textbox" id="email" name="email"onfocus="if(this.value=='Email') this.value='';" /><br />
        <br />
    
    <select id="swapImg" name="model" class="modelSelect" onchange="swapImage()" >
       <option value="images/1.jpg">A4</option>
    <option value="images/2.jpg" selected="selected">A6</option>
    <option value="images/3.jpg">A8</option>
    </select>
        <br />
        <br />
          <input type="submit" name="submit" class="butt" value="Send"  />
           <span class="buttonText">We'll Call you Back!</span>
     </form> 
    
    <script type='text/javascript'>
        var name=document.getElementById('name');
         if (name.value == null || name.value==""){
             errors['no_name']="Please enter your name";
         }
         //Repeat something similar for each field
    
         //Display all errors on the same page in the error box
         error_box=document.getElementById('error-box');
    
         for(error in errors){
             error_box.innerHTML=error.value + "<br/>";
         }
    </script>
    

    【讨论】:

      【解决方案4】:

      Javascript 将是实现这一目标的最佳方式,但是没有它也可以做到。为了完成它,您必须使用自我定位表单而不是外部脚本。这意味着form 的动作属性是它自己的脚本。以下是自我定位表单的基本布局示例:

      <?php
          if(isset($_POST)){
              $correct = true;
      
              //ENTER VERIFICATION CODE HERE. IF AN ELEMENT VERIFIES, LEAVE IT BE. IF AN ELEMENT DOES NOT VERIFY, CHANGE THE POST VALUE TO THE ERROR MESSAGE.
      
              if($_POST['number']=""){
                  $_POST['number'] = "* Please enter your phone number";
                  $correct = false;
              }else if(!is_numeric($_POST['number'])){
                  $_POST['number'] ='* Please enter only numbers 0-9.';
                  $correct = false;  
              }
      
              //AND SO ON FOR ALL INPUT ELEMENTS
      
              if($correct){
      
                  //SEND EMAIL CODE HERE
      
              }else{
      
                  //DISPLAY FORM WITH POST VARIABLES AS THE VALUE ATTRIBUTE
      
                 echo "<input type='text' name='number' value='" . $_POST['number'] . "'>";
      
                 //AND SO ON FOR ALL FORM ELEMENTS
              }
          }else{
              //DISPLAY FORM AS USUAL
          }
      

      代码回顾:如果设置了$_POST,则验证数据。如果元素未验证将无效的$_POST 值更改为错误消息,则使用这些$_POST 值构建下一个表单。如果所有元素都验证,则发送电子邮件。如果没有设置$_POST,那么就照常显示表单,因为我们知道用户还没有输入任何数据。祝你好运!

      【讨论】:

        【解决方案5】:

        您必须使用 javascript 在浏览器端进行验证。

        您可以使用纯 javascript 或 jquery 插件:

        Javascript

        function validateForm()
        {
        var x=document.forms["myForm"]["fname"].value;
        if (x==null || x=="")
          {
          alert("First name must be filled out");
          return false;
          }
        }
        

        在此处获取更多信息: http://www.w3schools.com/js/js_form_validation.asp

        使用 Jquery 你可以这样使用: http://jqueryvalidation.org/files/demo/

        【讨论】:

          猜你喜欢
          • 2014-01-30
          • 2015-04-17
          • 1970-01-01
          • 2021-10-23
          • 1970-01-01
          • 1970-01-01
          • 2021-10-12
          • 2012-02-15
          • 1970-01-01
          相关资源
          最近更新 更多