表格验证而不会丢失表格数据

时间:2014-03-22 18:19:46

标签: php forms submit

我已经在PHP中设置了一个带有验证的表单。我面临的问题是,单击提交按钮后会发生验证。单击提交按钮时,表单值将被删除。如果存在验证错误,则用户需要再次填充所有值,而不仅仅是错误1。是否有一种方法,一旦单击提交按钮,表单值不会被删除?

<tr>
<td><label for="email_address">Email Address:</label> <input type="text" name="email_address" id="email_address" required /></td>
</tr>
<tr>
<td><label for="password">Password:</label> <input type="password" size="25" maxlength="25" name="password" id="password" required /></td>
</tr>
<tr>
<td><label for="password2">Re-enter Password:</label> <input type="password" size="25" maxlength="25" name="password2" id="password2" required /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
<tr>
<?php
if(isset($_POST['submit'])){
$email_address = $_POST['email_address'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email_address)) {
?>
<td><?php echo "Enter Valid Email Address"; ?></td>
<?php
}
elseif ($password2 !== $password) {
?>
<td><?php echo "Passwords don't match"; ?></td>
<?php
}

1 个答案:

答案 0 :(得分:3)

您需要将用户输入回显到输入标记的值。这些形式被称为&#34;粘性形式&#34;(因为用户输入在提交后粘贴到表单上)。尝试做这样的事情 -

<input type="text" name="email_address" value="<?php echo (isset($_POST['email_address']))?$_POST['email_address']:'';?>" id="email_address" required />
                             Added this ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

这基本上回应了用户在值字段中输入的最后一个条目。尝试在每个输入标记中执行此操作。