【问题标题】:How to stop the form input data from erasing after php validation invalid = true?php验证无效=真后如何阻止删除表单输入数据?
【发布时间】:2014-07-21 01:25:20
【问题描述】:

我有一个用户输入数据的表单,例如名字和姓氏等。我有 PHP 验证来检查空字段。问题是单击提交按钮时,当字段为空时,整个表单数据都会被删除。

我在下面尝试了这种方法。

<input type="text" value="<?php echo $_POST["UserName"]; ?>"" name="UserName"   
id="UserName" size="20" /> 

但是当表单第一次加载时,文本框里面是这个

<br /><b>Notice</b>:  Undefined index: UserName in ...... on line <b>477</b><br />

有没有办法阻止表格被清除?或将数据回显到字段中?

【问题讨论】:

    标签: php html forms validation


    【解决方案1】:

    替换这个:

    value="<?php echo $_POST["UserName"]; ?>"
    

    在你的代码中:

    <?php if(isset($_POST["UserName"])) echo $_POST["UserName"]; ?>
    

    【讨论】:

      【解决方案2】:

      这里的问题是您没有检查 $_POST["UserName"] 是否已初始化,如果未初始化,您将抛出错误。检查 isset:

         <input type="text" value="<? if isset($_POST["UserName"]) { echo $_POST["UserName"]; } ?>" name="Givenname" id="Givenname" size="20" /> 
      

      【讨论】:

      • 请在您的 sn-p 中添加一些解释:问题是什么,以及您的代码如何解决它。
      【解决方案3】:

      检查$_POST["UserName"] isset,试试这个:

      <input type="text" value="<?php echo isset($_POST["UserName"]) ? $_POST["UserName"] : ''; ?>" name="Givenname"   
      id="Givenname" size="20" /> 
      

      【讨论】:

        【解决方案4】:

        我认为您正在使用这样的重置按钮:

        <input type="reset" />
        

        试试这个:

        <input type="submit" />
        

        如果您正在尝试第二个,则在每个输入中使用 required ,例如:

        <input required type="text" />
        

        【讨论】:

        • 不,我有两个按钮,一个用于 type="submit",一个用于 type="reset" @Mifmif,他的回答有效!
        【解决方案5】:

        您的表单没有被清除或删除。但是您正在加载一个带有新表单的新页面。

        您尝试加载新表单是一次不错的尝试,但您需要更改

        <input type="text" value="value="<?php echo $_POST["UserName"]; ?>"" name="UserName"    id="UserName" size="20" />
        

        进入

        <input type="text" value="<?php echo isset($_POST["UserName"])?$_POST["UserName"]:""; ?>" name="UserName" id="UserName" size="20" /> 
        

        所以删除第二个value=" 和相应的",它们本不应该存在。并在尝试回显之前检查变量是否可用。

        除此之外,您可能还希望在服务器端验证之上使用 Javascript 进行客户端验证。 (顺便说一句,永远不要只进行客户端验证,因为这可能会被最终用户愚弄。)

        你可以做的是把你的&lt;form&gt;标签改成这样:

        <form action="..." method="post" onsubmit="if (document.getElementById('UserName').value == '') { alert('UserName is still empty'); return false; }">
        

        当用户名仍然为空时,这将阻止表单被发送到 PHP。从而防止页面被重新加载和表单被清除。

        【讨论】:

        • 第二个“值”在这里输入有误,抱歉。是的,我确实有客户端验证。不过还是谢谢你的信息。
        • @user3636895 如果您已经进行了客户端验证,那么为什么还要担心表单字段会被清空呢?如果用户通过摆弄 javascript 来欺骗客户端验证,那么让他面对清除的表单字段。
        【解决方案6】:

        PHP 表单通常会在错误验证时丢弃输入的数据,即使在输入字段中回显它会缓存成功提交的条目,并且可以理解,删除不允许的数据将是默认行为。但是,在 textarea 中重新输入大量文本可能会非常困难,并且它的突然消失可能会让用户感到意外,尤其是由于字符数限制等简单原因.

        使用错误验证设置 $_POST['UserName'] 值应保留字段输入,而不允许其处理。该示例使用一个变量来缓存数据并将其回显到输入字段中。

        更新:脚本已更新为包含同一表单的多个提交按钮,以及成功消息数组的选项。

        更新:脚本已更新为包含一个 exit() 选项以及一个文本区域。

        • 定义了用户名和名字允许的字符,并将 使用大写 A-Z 或特殊字符触发错误。

        UserName 使用错误数组,而 First Name 使用 exit() 停止 整个脚本。

        文本框余量也会触发大写 A-Z 或 特殊字符,并使用 exit() 停止脚本。

        表单数据将在错误信息、exit() 页面返回和成功发送时保留。

        成功发送时打印表单结果。

            <?php
            /* Define variables and set to empty values.*/
            $username=$first_name=$textbox='';
            /* If using non-array success variable, initialize it as a string:
            $success='';
            Otherwise, define as an array. */
            /* Submit button is clicked, start validation.
            Separate multiple submit buttons (for the same form) with || (|| = OR):
            */
            if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
            // Define error and success messages as arrays to display in a list.
            $error=array();
            $success=array();
        
            // Validate user input and error characters not lowercase a-z or 1-9.
            if (!empty($_POST['UserName'])) {
            /* Trim outside whitespace and sanitize user input.
            A custom function or purifier could well be used. */
            $username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
            if (preg_match("/^[a-z0-9]+$/", $username)) {
            /*
            if (preg_match("/^[a-z0-9]+$/", trim($_POST['UserName']))) {
            $username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
            }
            can be placed here instead, however input data will likely not be preserved on error. */
            // Data is acceptable, continue processing...
            }
            else {
            // Data is not accepted, set value to prevent loss on error and echo input without processing.
            $error[]='User Name can only contain lowercase a-z and 0-9.';
            $username=$username;
            /* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether:
            $username=$username;
            exit ("Username may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
            */
            }
            }
            else {
            $error[]="Please enter a User Name.";
            }
        
            if (!empty($_POST['first_name'])) {
            /* Trim outside whitespace and sanitize user input.
            A custom function or purifier could well be used. */
            $first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
            if (preg_match("/^[a-z0-9]+$/", $first_name)) {
            /*
            if (preg_match("/^[a-z0-9]+$/", trim($_POST['first_name']))) {
            $first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
            }
            can be placed here instead, however input data will likely not be preserved on error. */
            // Data is acceptable, continue processing...
            }
            else {
            // Data is not accepted, set value to prevent loss on error and echo input without processing.
            /* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
            $first_name=$first_name;
            exit ("First Name may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
            /*
            $error[]='First Name may only contain lowercase a-z and 0-9.';
            $first_name=$first_name;
            */
            }
            }
            else {
            $error[]="Please enter a First Name.";
            }
        
            if (!empty($_POST['textbox'])) {
            /* Trim outside whitespace and sanitize user input.
            A custom function or purifier could well be used. */
            $textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
            if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", $textbox)) {
            /*
            if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", trim($_POST['textbox']))) {
            $textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
            }
            can be placed here instead, however input data will likely not be preserved on error. */
            // Data is acceptable, continue processing...
            }
            else {
            // Data is not accepted, set value to prevent loss on error and echo input without processing.
            /* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
            $textbox=$textbox;
            exit ("Textbox input may only contain spaces, lowercase a-z, and 0-9. Use the Back-button to try again.");
            /*
            $error[]='Textbox input may only contain spaces, lowercase a-z, and 0-9.';
            $textbox=$textbox;
            */
            }
            }
            else {
            $error[]="Please enter Textbox content.";
            }
        
            // If no errors, process data.
            if (empty($error)) {
            if (isset($_POST['submit_one'])) {
            /* Sanitized submit button per rule #1: never trust user input. Remove sanitization if it causes a system error.
            Reiterating ($_POST['submit'] is helpful when using multiple submit buttons.
            Wrap each function in the additional submit isset, and end functions with closing (empty($error) else statement. */
            $_POST['submit_one']=trim(htmlspecialchars($_POST['submit_one'], ENT_QUOTES));
            /* Post data or send email, and print success message.
            The array is option. Do not define as an array or use[] to use as a simple variable. */
            // Processing data here, for example posting to a database ...
            $success[]="The submit_one Send Form request has been processed!";
            }
        
            if (isset($_POST['submit_two'])) {
            $_POST['submit_two']=trim(htmlspecialchars($_POST['submit_two'], ENT_QUOTES));
            // Processing data here, for example sending an email ...
            $success[]="The submit_two Process Form request has been sent!";
            }
            }
            /* If errors, show error message.
            The exit() option ends the script at the validation check .*/
            else {
            $error[]="Please correct the errors and try again.";
            }
            }
            ?>
            <!DOCTYPE html>
            <html>
            <head>
            <style type="text/css">
            .wrapper {margin: 2% auto; width: 500px;}
            textarea {text-align:left;}
            </style>
            </head>
        
            <body>
            <div id="anchor" class="wrapper">
            <div>
            <form name="data_form" action="#anchor" method="post">
            <table>
            <tr>
            <td colspan="2">
            <label for="UserName">User Name</label>
            <br>
            <input type="text" name="UserName" id="UserName" size="20" value="<?php echo $username; ?>" />
            </td>
            </tr>
            <tr>
            <td colspan="2">
            <label for="first_name">First Name</label>
            <br>
            <input type="text" name="first_name" id="first_name" size="20" value="<?php echo $first_name; ?>" />
            </td>
            </tr>
            <tr>
            <td colspan="2">
            <label for="textbox">Textbox</label>
            <textarea name="textbox" id="textbox" style="height:100px; width:98%;text-align:left;"><?php echo $textbox; ?></textarea>
            </td>
            </tr>
            <tr>
            <td>
            <input type="submit" name="submit_one" id="submit_one" value="Send Form">
            </td>
            <td>
            <input type="submit" name="submit_two" id="submit_two" value="Process Form">
            </td>
            </tr>
            </table>
            </form>
            </div>
            <div>
            <?php
            /* Print errors as a list or print success message.
            Separate multiple submit buttons with ||. */
            if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
            if (!empty($error)) {
            echo '<h4>The form was not sent due to the following errors:</h4>
            <ul>';
            foreach ($error as $message) {echo '<li>'. $message . '</li>';
            }
            echo '</ul>';
            }
            /* Print success confirmations as a list for processed input. */
            else {
            echo '<h4>The form has been sent!</h4>
            <ul>';
            foreach ($success as $message) {echo '<li>'. $message . '</li>';}
            /* If using a success variable without defining it as an array,
            initialize it as a variable at the top of the script,
            then print variable without <ul>s and foreach loop:
            echo '<p>' . $success . '</p>';
            */
            echo '</ul>
            <h4>Processed Data:</h4>
            <ul>
            <li>User Name: ' . $username . '</li>
            <li>First Name: ' . $first_name . '</li>
            <li>Textbox: <br>' .
            /* Replace $textbox new lines with <br> tags. */
            nl2br($textbox) .
            '</li>
            </ul>';
            }
            /* Unset foreach loop data. */
            unset($message);
            }
            ?>
            </div>
            </div>
            </body>
            </html>
        

        【讨论】:

        • 在脚本中添加了 preg_match 结束 ')' 和结束表单标签。不确定语法错误如何通过测试和简单的视觉,归因于编码之谜。
        • 更新此脚本是一个相当漫长的过程。希望它对需要具有有效验证的良好实体表单模板的人有用。
        • 更新:preg_match 代码可以替换为 !preg_match 以通过消除空的成功短语来简化验证。例如: if(!preg_match("/^[A-Za-z0-9\ \,.+-(\s*\n){2}]+$/i", $textbox)) { $文本框=$文本框; exit ("文本框输入只能包含空格、AZ az 0-9 和 ,.+-。请使用后退按钮重试。");} . 正则表达式还包括使用不区分大小写的修饰符'i'、大写字符和 ,.+-_ 作为允许指定字符的示例。
        猜你喜欢
        • 1970-01-01
        • 2021-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-07
        • 1970-01-01
        • 1970-01-01
        • 2019-12-11
        相关资源
        最近更新 更多