PHP - 如果表单验证失败,则在文本字段内显示错误消息

时间:2014-05-13 13:27:50

标签: php forms validation

嗨,请原谅新手问题,因为我还在学习PHP。我试图做一个基本的表格验证。我试图让验证时发现的任何错误在表单字段中以红色显示。如果没有找到错误,表单应该重定向到感谢页面。

我已经写了一个基本的验证,但我现在仍然坚持如何正确实现它。

我的问题是:

  1. 如何在表单字段中显示错误消息而不发送表单?
  2. 如果没有发现错误,我如何处理发送表单?
  3. 我的代码如下:

    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
    

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

5 个答案:

答案 0 :(得分:2)

您必须使用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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

要验证表单中的数据而不提交,您必须使用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>

答案 3 :(得分:1)

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

<?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,则照常显示表单,因为我们知道用户尚未输入任何数据。祝你好运!

答案 4 :(得分:0)

您必须使用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/