简体   繁体   中英

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:

<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.

Further I would like to prevent the user to enter special characters, such as: ', ", `, ´,.. How can I do this in 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. By the time your js function executes, your php was already been executed on server.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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