【问题标题】:PHP- Validation message under text fieldPHP-文本字段下的验证消息
【发布时间】:2016-03-07 04:34:21
【问题描述】:

对此很陌生。我的验证代码运行良好。

但是,我试图让我的消息在每个文本字段下回显。

我尝试将回显更改为错误消息(将所有回显更改为$c_errorErr/$c_pass1Err),然后在输入字段旁边将echo $c_errorErr/$c_pass1Err 包装在跨度类中。

但是,此方法只会使我的验证消息停止工作。任何建议

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
        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>";
            }
        }
        ?>

【问题讨论】:

    标签: php html forms


    【解决方案1】:

    这是我的 2 美分价值(无依赖性):

    1. 使用 javascript 验证以获得更好的可用性。
    2. 不要在整个 php-ing 中回显。将错误消息保存在数组中。您可以为您拥有的每个表单元素扩展数组。
    3. 在页面加载后向表单控件添加验证事件,而不是弄乱 html。

    这并不是为了满足您的确切需求,因为我不知道这些需求是什么,但我希望它能回答您的基本问题。

    在此示例中,任何具有“verify-me”类的表单元素都将由 JS verifyData 函数进行验证。该函数使用控件值作为数据,使用控件名称作为验证方法。您可以根据需要添加任意数量的元素。

    我复制了您在 PHP 验证中使用的 'verify-as-you-go' 方法,但如果您有很多表单元素,您可以使用类似于此处显示的 JS 方式的 switch 语句来保持代码更紧凑.

    希望你觉得这很有用。

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

    【讨论】:

      【解决方案2】:

      我想在您的 PHP 代码之上提供一个 JS 解决方案。对于最终用户,您需要为他们提供实时反馈。在没有原始 POST 数据的情况下发布和返回对于最终用户来说并不理想;他们很生气。

      以下只是一个示例,您可以使用它来操作和制作您自己的示例。有更多 JS 知识的人可能会进一步清理和简化代码。

      关于使用您的示例和代码的 PHP 解决方案;出错时,我真的不明白你为什么要重复你的错误。我会将它们保存到您的变量中并回显变量。换句话说:

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

      然后在表单字段下方回显您的变量。

      以下是一个 JS 解决方案示例,它将在用户键入时显示错误。我希望这能指导你。

      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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-30
        • 2012-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多