简体   繁体   English

在PHP和JavaScript中验证表单

[英]Validate form in PHP and JavaScript

I am creating a simple registration form page(register.html): First Name, Last Name, Email, Username, Password, Confirm Password. 我正在创建一个简单的注册表单页面(register.html):名字,姓氏,电子邮件,用户名,密码,确认密码。 I have it set to validate the input client side in JavaScript and if that passes it goes to register.php which validates the data on the back end before making it safe and adding it to the database. 我设置了它来验证JavaScript中的输入客户端,如果通过了,它将转到register.php,后者在确保安全并将其添加到数据库之前先验证后端的数据。 All of that is working fine. 所有这些都很好。

However, there is a problem if say for example the validation on the back end fails. 但是,如果说例如后端的验证失败,就会出现问题。 I don't want the client to lose all the information they entered and have to do it all again, but since it already loaded register.php all that form data is now sitting in the PHP script but on a new page. 我不想让客户端丢失他们输入的所有信息,而必须再次做所有事情,但是由于它已经加载了register.php,所有这些表单数据现在都位于PHP脚本中,但是位于新的页面上。 And I am unsure how to deal with this problem. 我不确定如何处理这个问题。 I could create a duplicate form on the register.php page and use the PHP script to refill the form if it fails on the back end. 我可以在register.php页面上创建一个重复的表单,并在后端失败时使用PHP脚本重新填充表单。 But if I am going to do that I might as well just put the PHP code into my register.html and run it all that way. 但是,如果要执行此操作,则最好将PHP代码放入我的register.html中,然后一直运行。 But when I change action="register.html" to action="" and put my PHP code in there, nothing happens. 但是,当我将action =“ register.html”更改为action =“”并将PHP代码放入其中时,什么也没发生。 I've searched around and looked into isset but that doesn't seem to run either, the HTML page just reloads and clears all the fields, and I don't even see any echoes or anything. 我四处搜索并查看了isset,但是似乎也没有运行,HTML页面只是重新加载并清除了所有字段,而且我什至看不到任何回声或任何东西。

    <!DOCTYPE HTML>
<html>
    <head>
        <title>Family Beacon Registration</title>
        <style>
            .required {color: #FF0000;}
            .error {color: #FF0000;}
        </style>
        <script type="text/javascript">
            function validate()
            {
                var hasErrors = false;

                var first_name = document.forms["registration_form"]["first_name"].value;
                if(first_name == "")
                {
                    document.getElementById("first_name_error").innerHTML = "* First Name is a required field";
                    hasErrors = true;
                }
                else
                    document.getElementById("first_name_error").innerHTML = "*";

                var last_name = document.forms["registration_form"]["last_name"].value;
                if(last_name == "")
                {
                    document.getElementById("last_name_error").innerHTML = "* Last Name is a required field";
                    hasErrors = true;
                }
                else
                    document.getElementById("last_name_error").innerHTML = "*";

                var email = document.forms["registration_form"]["email"].value;
                if(email == "")
                {
                    document.getElementById("email_error").innerHTML = "* Email is a required field";
                    hasErrors = true;
                }
                else if(email.length > 40)
                {
                    document.getElementById("email_error").innerHTML = "* Email must be less than 40 characters in length.";
                    hasErrors = true;
                }
                else if(email.indexOf("@") == -1)
                {
                    document.getElementById("email_error").innerHTML = "* A valid e-mail address is required";
                    hasErrors = true;
                }
                else
                    document.getElementById("email_error").innerHTML = "*";

                var username = document.forms["registration_form"]["username"].value;
                if(username == "")
                {
                    document.getElementById("username_error").innerHTML = "* Username is a required field";
                    hasErrors = true;
                }
                else if(username.length < 3 || username.length > 20)
                {
                    document.getElementById("username_error").innerHTML = "* Username must be between 3 and 20 characters in length";
                    hasErrors = true;
                }
                else
                    document.getElementById("username_error").innerHTML = "*";

                var password = document.forms["registration_form"]["password"].value;
                if(password == "")
                {
                    document.getElementById("password_error").innerHTML = "* Password is a required field";
                    hasErrors = true;
                }
                else if(password.length < 8 || password.length > 20)
                {
                    document.getElementById("password_error").innerHTML = "* Passwords must be between 8 and 20 characters in length";
                    hasErrors = true;
                }
                else
                    document.getElementById("password_error").innerHTML = "*";

                var confirm_password = document.forms["registration_form"]["confirm_password"].value;
                if(confirm_password == "")
                {
                    document.getElementById("confirm_password_error").innerHTML = "* Confirm Password is a required field";
                    hasErrors = true;
                }
                else if(confirm_password != password)
                {
                    document.getElementById("confirm_password_error").innerHTML = "* Passwords do not match";
                    document.getElementById("password_error").innerHTML = "* Passwords do not match";
                    hasErrors = true;
                }
                else
                    document.getElementById("confirm_password_error").innerHTML = "*";

                return !hasErrors;
            }
        </script>
    </head>
    <body>  
        <h2>Family Beacon Registration</h2>
        <p><span class="required" id="required">* required field</span></p>
        <form name="registration_form" action="register.php" onsubmit="return validate();" method="post">
            First Name:<input type="text" name="first_name" id="first_name" />
            <span class="error" id="first_name_error">* </span><br><br>
            Last Name:<input type="text" name="last_name" id="last_name" />
            <span class="error" id="last_name_error">* </span><br><br>
            E-Mail:<input type="text" name="email" id="email" />
            <span class="error" id="email_error">* </span><br><br>
            Username:<input type="text" name="username" id="username" />
            <span class="error" id="username_error">* </span><br><br>
            Password:<input type="password" name="password" id="password" />
            <span class="error" id="password_error">* </span><br><br>
            Confirm Password:<input type="password" name="confirm_password" id="confirm_password" />
            <span class="error" id="confirm_password_error">* </span><br><br>
            <input type="reset" name="reset" value="Reset" />
            <input type="submit" name="submit" value="Register" />
        </form>
    </body>
</html>

First of all, One of your wrong concept is to put PHP code in a HTML extension file named register.html which will never work. 首先,您的错误概念之一是将PHP代码放入名为register.html的HTML扩展文件中,该文件将永远无法使用。 2nd thing is there are 3 solutions for this problem - Using AJAX Call - Using Self execution PHP file with the form and code. 第二件事是针对此问题有3种解决方案-使用AJAX调用-使用带有格式和代码的自执行PHP文件。 - Using Session (Which I prefer the least solution). -使用会话(我更喜欢最少的解决方案)。

For the first solution is the best way to use JQuery with AJAX call. 对于第一个解决方案,是将JQuery与AJAX调用结合使用的最佳方法。 To do so just use an ID for the form like this 为此,只需为这样的表单使用一个ID

   <form id="myForm">
    Your Form element goes here...
   </form>

Then use jquery just like this 然后像这样使用jquery

<script type='text/javascript'>
 $(document).ready(function(){
   $("#myForm").submit(function(){
     Your Validation code goes here.If all is ok then ...
     $.post("your_php_file_path.php",$(this)..serializeArray(),function(data){
   //here is the data is the echo you did in that php file
   //like echo "OK",you'll find data is set as string "OK"
     });
   });
});
</script>

Second is same page PHP and form works like this 第二个是同一页的PHP和表单,就像这样

<form action='<?php echo $_SERVER["PHP_SELF"] ?>' method='post'>
Your Form element like this
<input type='text' name='username' value='<?php echo isset($_POST['username'])?$_POST['username']:"" ?>'
</form>

And at the very top your page use php as this 并且在您的页面的最顶部使用php作为

<?php
if(count($_POST)){
//Your PHP code for validation and database insert
}
?>

This way you can handle error so easily like this 这样,您可以像这样轻松地处理错误

<?php
if(count($_POST)){
//Your PHP code for validation and database insert
if(your_error_condition_occur){
   $Error = "Error Message";
  }
}
?>

And in HTML Section use this 在HTML部分中使用此

 <?php
  if(isset($Error)){
   echo $Error;
   }
 ?>

You can use session for page to page data transfer without loosing them but usually session is used for login verification so I say don't use that. 您可以使用会话进行页面到页面的数据传输而不会丢失它们,但是通常会话用于登录验证,所以我说不要使用它。

What I do, which may work for you, is: 我可能为您工作的是:

Use jquery $(window).on("beforeunload" 使用jquery $(window).on("beforeunload"

so something like: 所以像这样:

$(window).on("beforeunload", function() { 
    //get all the data from inputs
    //set cookie with JSON.stringify(yourData)
})

Then on body load: 然后在身体负荷上:

if your cookie exists, JSON.parse it and put it into your inputs 如果您的Cookie存在,则JSON.parse并将其放入您的输入中

Edit: I can provide some example code should you want it. 编辑:如果需要,我可以提供一些示例代码。 Also, upon successful submission, in the php, do something like unset($_COOKIE['yourcookie']) so that upon successful submission your form doesn't keep their inputs :) 另外,在成功提交后,在php中,执行诸如unset($_COOKIE['yourcookie'])以便在成功提交后,您的表单不会保留其输入内容:)

Read about AJAX: https://www.w3schools.com/js/js_ajax_php.asp 了解有关AJAX的信息: https//www.w3schools.com/js/js_ajax_php.asp

AJAX means: Asynchronous JavaScript and XML AJAX的意思是: 异步 JavaScript和XML

Asynchronous menas, that you will be NOT redirected to this file. 异步状态,您将不会被重定向到该文件。 You will stay in your file and wait for server response. 您将保留在文件中,等待服务器响应。 If the response will be negative, you can to show some info for user, and if the response will be positive, you can redirect user to another page. 如果响应为否定,则可以为用户显示一些信息,如果响应为肯定的,则可以将用户重定向到另一个页面。 Until the response wil be positive, you do not need to redirect user to another page, so you can keep your data in input fields. 在响应为肯定之前,您无需将用户重定向到另一个页面,因此可以将数据保留在输入字段中。

Instead of using html post to register.php in a form, i recommend using Ajax call with javascript and even simpler with jQuery, if you have it loaded, you could do something like this: 我建议不要使用html post形式的register.php,而是建议将Ajax调用与javascript一起使用,甚至更简单地与jQuery一起使用,如果加载了它,则可以执行以下操作:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Family Beacon Registration</title>
        <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
        <style>
            .required {color: #FF0000;}
            .error {color: #FF0000;}
        </style>
    </head>
    <body>  
        <h2>Family Beacon Registration</h2>
        <p><span class="required" id="required">* required field</span></p>
        <div id="form">
            First Name:<input type="text" name="first_name" id="first_name" />
            <span class="error" id="first_name_error">* </span><br><br>
            Last Name:<input type="text" name="last_name" id="last_name" />
            <span class="error" id="last_name_error">* </span><br><br>
            E-Mail:<input type="text" name="email" id="email" />
            <span class="error" id="email_error">* </span><br><br>
            Username:<input type="text" name="username" id="username" />
            <span class="error" id="username_error">* </span><br><br>
            Password:<input type="password" name="password" id="password" />
            <span class="error" id="password_error">* </span><br><br>
            Confirm Password:<input type="password" name="confirm_password" id="confirm_password" />
            <span class="error" id="confirm_password_error">* </span><br><br>
            <input type="reset" name="reset" value="Reset" />
            <input id="formSubmit" type="submit" name="submit" value="Register" />
        </div>
        <script>
            $(function() {
                $("#formSubmit").click(function() {
                    var hasErrors = false,
                        first_name = document.forms["registration_form"]["first_name"].value,
                        last_name = document.forms["registration_form"]["last_name"].value,
                        email = document.forms["registration_form"]["email"].value,
                        username = document.forms["registration_form"]["username"].value,
                        password = document.forms["registration_form"]["password"].value,
                        confirm_password = document.forms["registration_form"]["confirm_password"].value;
                    if(first_name == "") {
                        document.getElementById("first_name_error").innerHTML = "* First Name is a required field";
                        hasErrors = true;
                    } else {
                        document.getElementById("first_name_error").innerHTML = "*";
                    }
                    if(last_name == "") {
                        document.getElementById("last_name_error").innerHTML = "* Last Name is a required field";
                        hasErrors = true;
                    } else {
                        document.getElementById("last_name_error").innerHTML = "*";
                    }
                    if(email == "") {
                        document.getElementById("email_error").innerHTML = "* Email is a required field";
                        hasErrors = true;
                    } else if(email.length > 40) {
                        document.getElementById("email_error").innerHTML = "* Email must be less than 40 characters in length.";
                        hasErrors = true;
                    } else if(email.indexOf("@") == -1) {
                        document.getElementById("email_error").innerHTML = "* A valid e-mail address is required";
                        hasErrors = true;
                    } else {
                        document.getElementById("email_error").innerHTML = "*";
                    }
                    if(username == "") {
                        document.getElementById("username_error").innerHTML = "* Username is a required field";
                        hasErrors = true;
                    } else if(username.length < 3 || username.length > 20) {
                        document.getElementById("username_error").innerHTML = "* Username must be between 3 and 20 characters in length";
                        hasErrors = true;
                    } else {
                        document.getElementById("username_error").innerHTML = "*";
                    }
                    if(password == "") {
                        document.getElementById("password_error").innerHTML = "* Password is a required field";
                        hasErrors = true;
                    } else if(password.length < 8 || password.length > 20) {
                        document.getElementById("password_error").innerHTML = "* Passwords must be between 8 and 20 characters in length";
                        hasErrors = true;
                    } else {
                        document.getElementById("password_error").innerHTML = "*";
                    }
                    if(confirm_password == "") {
                        document.getElementById("confirm_password_error").innerHTML = "* Confirm Password is a required field";
                        hasErrors = true;
                    } else if(confirm_password != password) {
                        document.getElementById("confirm_password_error").innerHTML = "* Passwords do not match";
                        document.getElementById("password_error").innerHTML = "* Passwords do not match";
                        hasErrors = true;
                    } else {
                        document.getElementById("confirm_password_error").innerHTML = "*";
                    }

                    if(!hasErrors) {
                        $.post( "register.php", {
                            first_name: first_name,
                            last_name: last_name,
                            email: email,
                            username: username,
                            password: password,
                            confirm_password: confirm_password
                        })
                        .done(function(data) {
                            // Data is the PHP echoed output.
                            alert(data);
                        })
                        .fail(function() {
                            alert( "error" );
                        });
                    }
                });
            });
        </script>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM