【问题标题】:PHP - Redisplay forms with valid values in fields and error messages where validation failsPHP - 验证失败时在字段中显示有效值和错误消息的表单
【发布时间】:2014-01-30 03:50:58
【问题描述】:

我创建了一个 PHP 表单来获取 4 个文本字段名称、电子邮件、用户名和密码,并为这些设置了验证。我的代码当前正在正确验证并在代码验证与否时显示消息。 但是,我希望它在提交时保持正确验证的字段被填写,而那些验证失败的字段为空,并显示详细说明原因的错误消息。

到目前为止我有以下代码,主要是form.php:

    <?php
    $self = htmlentities($_SERVER['PHP_SELF']);
    ?>
    <form action="<?php echo $self; ?>" method="post">
        <fieldset>
        <p>You must fill in every field</p>
        <legend>Personal details</legend>
            <?php
            include 'personaldetails.php';
            include 'logindetails.php';
            ?>
            <div>            
                <input type="submit" name="" value="Register" />
            </div>
        </fieldset>
    </form>
    <?php
    $firstname = validate_fname();
    $emailad = validate_email();
    $username = validate_username();
    $pword = validate_pw();
    ?>

我的functions.php代码如下:

<?php
function validate_fname() {
    if (!empty($_POST['fname']))    {
        $form_is_submitted = true;
        $trimmed = trim($_POST['fname']);
        if  (strlen($trimmed)<=150  && preg_match('/\\s/', $trimmed))   {
            $fname = htmlentities($_POST['fname']);
            echo "<p>You entered full name: $fname</p>";
        }   else    {
                echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
        }   }
        }

function validate_email() {        
    if (!empty($_POST['email']))    {
        $form_is_submitted = true;
        $trimmed = trim($_POST['email']);
        if  (filter_var($trimmed, FILTER_VALIDATE_EMAIL))   {
            $clean['email'] = $_POST['email'];              
            $email = htmlentities($_POST['email']);

            echo "<p>You entered email: $email</p>";
        }   else    {
                echo "<p>Incorrect email entered!</p>";
        }   }   
        }

function validate_username() {
    if (!empty($_POST['uname']))        {
        $form_is_submitted = true;
        $trimmed = trim($_POST['uname']);
        if  (strlen($trimmed)>=5 && strlen($trimmed) <=10)  {
            $uname = htmlentities($_POST['uname']);
            echo "<p>You entered username: $uname</p>";
        }   else    {
                echo "<p>Username must be of length 5-10 characters!</p>";
        }   }   
    }

function validate_pw()  {
    if (!empty($_POST['pw']))   {
        $form_is_submitted = true;
        $trimmed = trim($_POST['pw']);
        if  (strlen($trimmed)>=8 && strlen($trimmed) <=10)  {           
            $pword = htmlentities($_POST['pw']);
            echo "<p>You entered password: $pword</p>";
        }   else    {
                echo "<p>Password must be of length 8-10 characters!</p>";      
        }   }
    }
?>

如何确保在按下提交时它会保留有效输入并清空返回错误消息的无效输入。

最好我还希望初始 if(!empty) 有一个备用的 else 条件。我最初有这个,但发现它会以错误消息开始表单。

最后,通过此表单注册后,如何将有效信息记录到外部文件中以用于检查登录详细信息?

非常感谢任何帮助。

【问题讨论】:

  • 您遇到了什么具体问题?数据验证/重新填充的哪一部分不适合您?你有没有做过任何调试来缩小它为什么不起作用?实际上,您根本没有显示任何可以在出错时将值填充回表单的代码。
  • 只需将输入值设置为来自帖子的 html 安全用户输入
  • 这个代码include 'personaldetails.php'; include 'logindetails.php';在哪里?将此添加到您的脚本顶部 error_reporting(E_ALL); ini_set('display_errors', 1) 以便您可以确定错误在哪里。

标签: php forms validation


【解决方案1】:

尝试对错误使用单独的变量,而不是将错误消息输出到input 字段。

您可以为此使用 global 变量,但我不喜欢它们。

登录.php

<?php 
$firstname = '';
$password  = '';
$username  = '';
$emailadd  = '';
$response  = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
    <fieldset>
        <p>Please enter your username and password</p>
    <legend>Login</legend>
        <div>
        <label for="fullname">Full Name</label>
            <input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
        </div>
        <div>
         <label for="emailad">Email address</label>
         <input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
        </div>
        <div>
        <label for="username">Username (between 5-10 characters)</label>
        <input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
        </div>
        <div>            
        <label for="password">Password (between 8-10 characters)</label>
        <input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
        </div>
        <div>            
            <input type="submit" name="" value="Submit" />
        </div>
    </fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
    print $response;         
}     
?>
//Footer stuff

登录进程.php

//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
    //Here we concatenate the return values of your validation functions.
    $response .= validate_fname();
    $response .= validate_email();
    $response .= validate_username();
    $response .= validate_pw();
}    
//...or footer stuff.

functions.php

function validate_fname() {
    //Note the use of global...
    global $firstname;
    if (!empty($_POST['fname']))    {
        $form_is_submitted = true;
        $trimmed = trim($_POST['fname']);
        if(strlen($trimmed)<=150  && preg_match('/\\s/', $trimmed)){
            $fname = htmlentities($_POST['fname']);
            //..and the setting of the global.
            $firstname = $fname;
            //Change all your 'echo' to 'return' in other functions.
            return"<p>You entered full name: $fname</p>";
        } else {
            return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
        }
    }
}

我不建议对表单之类的小东西使用包含,我发现它会很快把事情弄得一团糟。将所有“显示”代码保存在一个文件中,并仅在范围更改时将包含用于函数(就像您拥有的那样)和拆分文件。即您的 functions.php 文件目前处理验证,但您可能希望稍后创建一个新的包含来处理实际的登录或注册过程。

查看http://www.php.net/manual/en/language.operators.string.php 了解有关连接的信息。

【讨论】:

  • 您是否将 'echo' 替换为 'return' ?此外,您的 Sky Drive 没有反映我建议的更改,所以我不知道从哪里开始!
  • 我的问题确实是因为如果我使用 $_POST 作为文本字段的标签,那么它不会让我清除无效的输入。但是,如果我对文本字段使用变量,那么在提交时会显示正确的错误消息,但会清除所有输入数据。我需要的是让它保持经过验证的输入但清除不正确的输入 - 我需要一种方法来让它在第一次运行 register.php 时将保持输入的变量声明为空(否则字段中会充满错误消息)但不是在它更新表格。我知道这是我的错误所在。
  • 我将 register.php 中的变量声明为: $fname = ''; $电子邮件=''; $uname = ''; $pw = '';但是当函数运行并更新页面时,它会清空通过函数获得的变量的值。如果我使用 $POST,那么文本字段只保存输入的内容,而不管它是否验证。
  • 好的,我已将 cmets 添加到您的 SkyDrive。
  • 再次嗨 - 我尝试了您建议的更改,但效果相同。
猜你喜欢
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2012-04-08
  • 2021-10-12
  • 2012-02-15
相关资源
最近更新 更多