简体   繁体   English

防止Javascript验证失败后php执行代码,并防止JS使用某些字符

[英]Prevent php from executing code after Javascript validation fails and prevent some characters with JS

I have a user registration form and after the user has filled all informations I submit the entered values: 我有一个用户注册表,在用户填写完所有信息后,我提交输入的值:

<?php if (isset($_POST['submit'])) {
          echo '<script type="text/javascript">CheckPassword(document.userform.password);</script>';

        ## connect mysql server
            $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
            # check connection
            if ($mysqli->connect_errno) {
                echo "<p>Fehler Nummer {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
                exit();
            }
        ## query database
            # prepare data for insertion
            $username   = $_POST['username'];
            $password   = $_POST['password'];
            $first_name = $_POST['first_name'];
            $last_name  = $_POST['last_name'];
            $email      = $_POST['email'];

            # check if username and email exist else insert
            // u = username, e = emai, ue = both username and email already exists
           //the rest of the code is not important for this question

On the first line ( echo '<script... ) I call the following javascript function: 在第一行( echo '<script... ),我调用以下javascript函数:

<script type="text/javascript">
            function CheckPassword(inputtxt)   
            {   
                var passw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;  
                if(inputtxt.value.match(passw))   
                {   
                    alert("check");
                    return true;  
                }  
                else{
                    alert("!check");
                    return false;
                }
            }
        </script>

The call works perfectly but if the user has entered an invalid password I do not want to run the rest of the php code. 该调用工作正常,但是如果用户输入了无效密码,则我不想运行其余的php代码。

Further I would like to prevent the user to enter special characters, such as: ', ", `, ´,.. How can I do this in Javascript? 此外,我想防止用户输入特殊字符,例如:',',',',..。如何在Javascript中执行此操作?

You can not do this, you need to move your js validation function to on form submit because php runs server side, while js runs on client side. 您不能这样做,您需要将js验证功能移至表单提交上,因为php在服务器端运行,而js在客户端运行。 By the time your js function executes, your php was already been executed on server. 到您的js函数执行时,您的php已经在服务器上执行了。

The proper way of doing this is call your function on form submit. 正确的方法是在表单提交上调用函数。

Example: 例:

<form name="test_frm" id="test_frm" action="abc.php" onsubmit="return CheckPassword();">

Note: this is just an example 注意:这只是一个例子

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

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