简体   繁体   English

PHP-文本字段下的验证消息

[英]PHP- Validation message under text field

new to this. 新的。 my validation code works perfectly. 我的验证代码可以完美运行。

However, I am trying to get my message to echo under each text field. 但是,我试图让我的消息在每个文本字段下回显。

I have tried changing the echo to a error message (changing all the echo to $c_errorErr/$c_pass1Err ) and then echo $c_errorErr/$c_pass1Err next to the input field and wrapping this in a span class. 我尝试将回显更改为错误消息(将所有回显更改为$c_errorErr/$c_pass1Err ),然后在输入字段旁边echo $c_errorErr/$c_pass1Err并将其包装在span类中。

However, this method just stops my validation messages from working. 但是,此方法只会停止我的验证消息。 Any suggestions 有什么建议么

HTML 的HTML

            <!--                    <div id="first">-->
            <input type="email" id="email" name="email" placeholder="Email Address" value='' required>
            <br>

            <figure>
                <input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password"  maxlength="30" required><!--<span class="error"><?php //echo $c_pass1Err;            ?></span>-->
                <input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err;            ?></span>-->
                <div id="messages"></div>
            </figure>
            <p class="remember_me">
            </p>
            <input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
            <br>
        </form>

PHP 的PHP

   <?php
        if (isset($_POST['submit'])) {
            $c_email = $_POST['email'];
            $c_pass1 = $_POST['pass1'];
            $c_pass2 = $_POST['pass2'];
            $c_emailErr = $pass1Err = $pass2Err = "";
            //$c_email = $c_pass1 = $c_pass2 = "";
           // Remove all illegal characters from email
           //$c_email = filter_var($c_email, FILTER_SANITIZE_EMAIL);
           //Checking the email address
            if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
                echo  ("<b  id='email'> This is a valid email address </b>");
            } else {
                echo ("<b id='email'> Email is not a valid email address</b>");
            }
        if (strlen($c_pass1) <= '8') {
     echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
        //check passwords
    }elseif ($c_pass1 == $c_pass2) {
                        $q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
                $stmt = mysqli_prepare($dbc, $q);
                //new
                // $stmt = mysqli_prepare($dbc, $insert_c);
                //debugging
                //$stmt = mysqli_prepare($dbc, $insert_c)  or die(mysqli_error($dbc));

                mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
                if ($q) {
                    echo "<script> alert('registration sucessful')</script>";
                }
            } else {
                echo "<b>Oops! Your passwords do not </b>";
            }
        }
        ?>

I wanted to offer a JS solution on top of your PHP code. 我想在您的PHP代码之上提供JS解决方案。 For end users, you want real time feedback for them. 对于最终用户,您需要他们的实时反馈。 Posting and being brought back without the original POST data isn't ideal for end users; 在没有原始POST数据的情况下进行发布和重新发送对于最终用户而言并不理想; they get annoyed. 他们很生气。

The below is just a sample that you can use to manipulate and make your own. 下面只是一个示例,您可以用来操作和制作自己的示例。 Someone with more JS knowledge could probably clean and streamline the code some more. 具有更多JS知识的人可能可以清理和简化代码。

As to the PHP solution using your example and code; 至于使用您的示例和代码的PHP解决方案; on error, I don't really see why you're echo'ing your errors. 如果出现错误,我真的看不到您为什么回显您的错误。 I would save them to your variables and echo the variables. 我会将它们保存到您的变量中并回显变量。 In other words: 换一种说法:

if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false)
{
    $c_emailErr = "<b  id='email'> This is a valid email address </b>";
}

Then echo your variable underneath the form field. 然后在表单字段下方回显您的变量。

The following is a JS solution sample that will display the errors as the user types. 以下是一个JS解决方案示例,该示例将根据用户类型显示错误。 I hope this guides you. 我希望这可以指导您。

 function validateEmail(email) { var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; return re.test(email); } function verifyPEmail() { var pEmail = $("#txtNewEmail").val(); if (pEmail != "" && validateEmail(pEmail) == false) { $("#divCheckValidEmail").html("<span style='color:red;'>Email Structure is Invalid</span>"); } else if (validateEmail(pEmail) == true) { $("#divCheckValidEmail").html("<span style='color:green;'>Valid Email Structure</span>"); } else if (pEmail == "") { $("#divCheckValidEmail").html("<span style='color:red;'>Missing Email</span>"); } } function verifyPass1() { var pass1 = $("#pass1").val(); if (pass1 == "" || pass1.length < 8) { $("#divCheckPass1").html("<span style='color:red;'>Password must be at least 8 characters long</span>"); } else { $("#divCheckPass1").html("<span style='color:green;'></span>"); } } function verifyPass2() { var pass1 = $("#pass1").val(); var pass2 = $("#pass2").val(); if (pass1 !== pass2) { $("#divCheckPass2").html("<span style='color:red;'>Password do not match</span>"); } else { $("#divCheckPass2").html("<span style='color:green;'>Passwords Match</span>"); } } $(document).ready(function() { $("#txtVerifyEmail").keyup(verifyPEmail); $("#pass1").keyup(verifyPass1); $("#pass2").keyup(verifyPass2); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script> <form action="index.php" name="formInput" method="POST" autocomplete="off"> <label class="input"><span class="fontBold fontItalic">Email address</span> <br> <input type="email" name="pgEmail" id="txtNewEmail" oninput="verifyPEmail();" value=""> </label> <div class="registrationFormAlert" id="divCheckValidEmail"></div> <label class="input"><span class="fontBold fontItalic">Password</span> <br> <input type="password" name="pass1" id="pass1" oninput="verifyPass1();" value=""> </label> <div class="registrationFormAlert" id="divCheckPass1"></div> <label class="input"><span class="fontBold fontItalic">Verify Password</span> <br> <input type="password" name="pass2" id="pass2" oninput="verifyPass2();" value=""> </label> <div class="registrationFormAlert" id="divCheckPass2"></div> </form> 

Here's my 2-cents worth (no dependencies): 这是我的2美分价值(无依赖项):

  1. validate with javascript for better usability. 使用javascript进行验证,以提高可用性。
  2. don't echo throughout the php-ing. 不要在整个php-ing中回显。 save the error messages in an array. 将错误消息保存在数组中。 You can extend the array for every form element you have. 您可以为您拥有的每个表单元素扩展数组。
  3. add verification events to form controls after the page loads, rather than cluttering up the html. 在页面加载后向表单控件添加验证事件,而不是使html变得混乱。

This is not intended to be a use-as-is form for your exact needs, since I can't know what those needs are, but I hope it answers your underlying questions. 因为我不知道这些需求是什么,所以这并不是为了满足您的确切需求,而是希望它能回答您的基本问题。

In this example, any form element with the class "verify-me" will be verified by the JS verifyData function. 在此示例中,任何带有“ verify-me”类的表单元素都将由JS verifyData函数进行验证。 This function uses the control value as data, and the control name for method of validation. 此函数使用控件值作为数据,并使用控件名称作为验证方法。 You can add as many elements as you need. 您可以根据需要添加任意数量的元素。

I copied the 'verify-as-you-go' method that you used in the PHP validation, but if you have many form elements, you can use a switch statement similar to the JS way shown here to keep the code tighter. 我复制了在PHP验证中使用的“ verify-as-you-go”方法,但是如果您有很多表单元素,则可以使用类似于此处所示JS方式的switch语句来使代码更加紧凑。

Hope you find this useful. 希望您觉得这个有帮助。

<?php
            $password = $c_email = $c_pass1 = $c_pass2 = $email_status = $password_status1 = $password_status2 = "";
            $err_array = array('email_err' => '', 'password_err1' => '', 'password_err2' => '');

        if (isset($_POST['submit'])) {
         $c_email = clean_input($_POST["email"]);
                        if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
                            // email okay
                        } else {
                                $err_array['email_err'] = 'Not a valid email';
                            }
         $c_pass2 = clean_input($_POST["c_pass2"]);         
         $c_pass1 = clean_input($_POST["c_pass1"]);

            if (strlen($c_pass1) <= '8') {  
                $err_array['password_err1'] = "Password must be at least 8 characters";
            } elseif ($c_pass1 == $c_pass2) {
                    // carry on with fucntions
                }   else {
                        $err_array['password_err2'] = "Ooops, passwords don't match";
                    }
        }

    function clean_input($data) {
         $data = trim($data);
         $data = stripslashes($data);
         $data = htmlspecialchars($data);
         return $data;
    }
    ?>
    <!doctype html>
    <html>
    <title>form validation</title>
    <style type = "text/css">
    .error 
    {
    color: red;
    }
    </style>
    <h1>Form</h1>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
         E-mail: <input type="text" name="email" class = "verify-me" value = "<?=$c_email?>">
         <span class="error"><?php echo $err_array['email_err']; ?></span>
         <br>
         Password: <input type="text" name="c_pass1" class = "verify-me" value = "<?=$c_pass1?>">
         <span class="error"><?php echo $err_array['password_err1']; ?></span>
         <br>
         Password again: <input type="text" name="c_pass2" class = "verify-me" value = "<?=$c_pass2?>">
         <span class="error"><?php echo $err_array['password_err2']; ?></span>
         <br><br>
         <input type="submit" name="submit" value="Submit"> 
    </form>

    </body>
    <script>
        //  set onclick and onchange events for all inputs with className: 'verify-me'
    var verify = document.getElementsByClassName('verify-me');
        for (var i = 0; i < verify.length ; i++)
            {
            verify[i].onclick = function () { resetError( this ); } ;
            verify[i].onchange = function () { verifyData( this, this.name ); } ;
            }
        //  this function to clear the error code when the input is edited 
        function resetError (inputElement) {
            inputElement.nextElementSibling.innerHTML = '';
        }

        //  check the item value, and run a test according to dataType.
        function verifyData(item, dataType) {
            switch (dataType) {

                case 'email':
                if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(item.value)) {
                        console.log('c_pass1 okay');
                    } else {
                        item.nextElementSibling.innerHTML = 'Not a valid email address';
                }
                break;

                case 'c_pass1':
                if (item.value.length >= 8) {
                    console.log('c_pass1 okay');
                } else {
                        item.nextElementSibling.innerHTML = 'Password must be 8 characters or more';
                    }
                break;

                case 'c_pass2':
                if (item.value == document.getElementById('c_pass1.value')) {
                    console.log('c_pass2 okay');
                } else {
                        item.nextElementSibling.innerHTML = 'Passwords do not match';
                    }
                break;
            }
        }
    </script>
    </html>

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

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