【问题标题】:How do I add PHP validation to my contact for如何将 PHP 验证添加到我的联系人
【发布时间】:2017-02-13 10:48:20
【问题描述】:

我使用 css、html、javascript 和一点 php 制作了一个网站。我将它托管在具有域名的托管站点上,但我遇到了表单的服务器端验证问题。

这只是一个简单的联系表格:

名字 姓 电子邮件 消息(文本区域) 提交按钮

我有 javascript 验证,它工作正常。除非输入正确数量的字符,否则表单根本不会提交,但显然如果用户禁用了 js,那将毫无用处。我也终于得到了使用 php 将表单通过电子邮件发送到我的个人电子邮件......但显然我也需要服务器端验证。

今天是我真正接触 php 的第一天,我希望在今天之前完成 php 验证,但是在我观看的所有视频中,我只是更加困惑。我要做的就是做到这一点,以便如果用户出于某种原因禁用了 javascript,或者如果他将字段留空,则表单将不会提交...

好吧,我今天整天都在做这个,打算将表格发送到我的电子邮件,我终于做到了。然后意识到我没有服务器端验证。我花了几个小时研究它并尝试它无济于事。这里的任何人都可以给我上面描述的那种表单的 php 验证代码吗?这是为我的商业网站准备的,所以我越早在上面有一个有效的联系表就越好...

这是我制作的 html 联系表。

<form action="message_sent.php" method="POST"      onSubmit="return validateTextbox();">

<p class="message">
<div class="row">

<label for="firstname"><!--First Name (Required):-->    </label>
<input type="text" id="firstname" name="first_name"  size="40" placeholder="First Name (Required)"></br> </br>   </div>


<div class="row">

<label for="lastname"><!--Last Name (Required):--> </label>
<input type="text" id="lastname" name="last_name"   size="40" placeholder="Last Name (Required)"/> </br>   </br></div>

<div class="row">
<label for="email"><!--Your Email (Required):--></label>
<input type="email" id="email" name="email" size="40"  placeholder="Email (Required)"/> </br> </br></div>

<!--<p class="yourMessage">Your Message (10 Character Minimum):</p>--> 
<textarea id="theform" rows="30" cols="80"  name="message" placeholder="Your Message (10 Character Minimum):"></textarea></br>

</p>

<input type="submit" name="submit" onclick="return val();"  value="SUBMIT">

</form>

</body>
</html>

这里是 javascript 验证:

/*============================ CONTACT US PAGE    ==========================*/

function validateTextbox() {


var box = document.getElementById("firstname");
var box2 = document.getElementById("lastname");
var box3 = document.getElementById("email");
var box4 = document.getElementById("theForm");



if (box.value.length < 1 || box2.value.length < 1 ||  box3.value.length < 5){
alert("You must enter a value");    

box.focus();
box.style.border = "solid 3px red";
   box2.focus();
   box2.style.border = "solid 3px red";
      box3.focus();
      box3.style.border = "solid 3px red";


    return false;
    }


}



        function val(){

            if(document.getElementById("theform").value.length < 10 
        && document.getElementById("theform").value.length > 0){

            alert("You must enter at least 50  characters. Tell us what you need so we can better assist you.");
            return false;

        }


        else  if(document.getElementById("theform").value.length === 0){

            alert("You cannot submit an empty form.");
            theform.focus();
            theform.style.border = "solid 3px red";
            return false;
        } 



    }


            /*function val(){

         if(document.getElementById("theform").value==null || document.getElementById("theform").value==""){
            alert("The Message field cannot be blank.");

            return false;                                               
    }


        */




    /*



*/




 /*=======================|| box4.value.length < 70) ================================================ */


   /*========= CONTACT  PAGE========================================*/

    /*
 function contactPage(){


alert("This Contact Form is NOT OPERATIONAL.");

这里是 php 提交成功页面...我曾经将表单发送到我的电子邮件的代码:

<?php



$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$message=$_POST['message'];

$to="default@email.com";
$subject="A visitor has sent you a new message";
$body="You have received a message from: \n\n 
First Name: $first_name\n 
Last Name: $last_name\n
Email: $email\n\n
MESSAGE: $message";

mail($to, $subject, $body);

print "<p>Message Sent! <a href='index.html'>Click.       here</a> to return to the homepage</p>"


?>

【问题讨论】:

  • 请张贴您的 POST 代码并展示您迄今为止所做的尝试。我们可以纠正和增强它。

标签: php forms validation contact


【解决方案1】:

简单完整的例子:

<!DOCTYPE HTML>  
<html>
    <head>
        <style>
            .error {color: #FF0000;}
        </style>
    </head>
    <body>
        <?php

            //Define variable as empty to avoid "undefined variable error".
            $FnameErr = $LnameErr = $emailErr = ""; //Each variable contain error string of specific field.
            $fname = $lname = $email = $message = ""; //Main inputed data of specific field


            if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if request is posted.

              //First name check
              if (empty($_POST["fname"])) {            // check if empty then assign a error string in spacific variable
                $FnameErr = "First Name is required";
              }else{                                   // if not empty then store as right data
                $fname = filter_data($_POST["fname"]); //filter with unexpected special char and trim.
              }

              //Last name
              if (empty($_POST["lname"])) {            // check if empty then assign a error string in spacific variable
                $LnameErr = "Last Name is required";  
              }else{                                   // if not empty then store as right data
                $lname = filter_data($_POST["lname"]); //filter with unexpected special char and trim.
              }

              //email
              if (empty($_POST["email"])) {            // check if empty then assign a error string in spacific variable
                $emailErr = "Email is required"; 
              } else {
                if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {  // validate email with php build-in fucntion.
                  $emailErr = "Invalid email format"; 
                }else{                                             // if not empty and valide email then store as right data
                  $email = filter_data($_POST["email"]);           //filter with unexpected special char and trim.
                }
              }

              //message with no validation
              if (empty($_POST["message"])) {
                $message = "";
              } else {
                $message = filter_data($_POST["message"]);
              }


              //Database query
              if($FnameErr =="" && $LnameErr =="" && $emailErr==""){
                //MYSQL insert statement that you know
                // $sql =  "INSERT INTO tablename .................."; values = $fname; $lname; $email; $message;
              }

            }


            // A function to trim data and remove special charecter
            function filter_data($data) {
              $data = trim($data);
              $data = stripslashes($data);
              $data = htmlspecialchars($data);
              return $data;
            }
          ?>


        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
            First Name: <input type="text" name="fname" value="">
            <span class="error">* <?php echo $FnameErr;?></span><br><br>

            Last Name: <input type="text" name="lname" value="">
            <span class="error">* <?php echo $LnameErr;?></span><br><br>

            E-mail: <input type="text" name="email" value="">
            <span class="error">* <?php echo $emailErr;?></span>
            <br><br>

            Message: <textarea name="message" rows="5" cols="40"></textarea>
            <br><br>

            <input type="submit" name="submit" value="Submit">  
        </form>

        <?php
          echo "<h2>Your Input:</h2>";
          echo $fname;
          echo "<br>";

          echo $lname;
          echo "<br>";
          echo $email;
          echo "<br>";
          echo $message;
        ?>
    </body>
</html>

【讨论】:

  • 应该对你在这里拥有的每个圈入口点提供一个规范的解释,如果你这样做,这个答案对于初学者和其他人来说会变得更加丰富。
  • 谢谢@Zanderwar,我一定要试试。
【解决方案2】:

这只是一个基本的空检查验证。

PHP 中的验证并不难。

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if(trim($_POST['firstname']) === ''){
      echo 'Please enter firstname';
   }
}

您还可以在此处了解一些验证 http://www.w3schools.com/php/php_form_validation.asp

【讨论】:

  • 好的,我在第一篇文章中添加了我的代码。它是 html、javascript 和 pbp 代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
相关资源
最近更新 更多