提交PHP后保留表单中的值数据

时间:2016-05-19 13:14:05

标签: php html forms validation

我看过其他帖子但无法解决问题。

我试图找到在发布后保留表单值的最简单方法。例如注册表格,

如果用户输入除一个字段(例如电子邮件地址)以外的所有正确数据,那么表单将通过PHP表单提交,如何保留有效的表单数据但删除无效的数据?

以下是我的表单代码:

<form action="./scripts/register.php" method="POST" name="registration" />
        Your Name: 
            <input class="submissionfield" type="text" name="name" required pattern="[a-zA-Z\s]+" title="Your name can only contain alphabetic characters" placeholder="Bob Smith"> 

        Username: &nbsp; 
            <input class="submissionfield" type="text" name="username" required pattern="[a-zA-Z0-9]+" title="Username can only contain alphabetic characters and/or numbers. (No Spaces)" placeholder="bsmith29">

        Email:
            <input class="submissionfield" type="email" name="email" required placeholder="name@email.com" title="Example email address: tom@smith.com"> 

        Password:
            <input class="submissionfield" type="password" name="password" required pattern="[a-zA-Z0-9]+" title="Password can only contain alphabetic characters and/or numbers. (No Spaces)" placeholder="Enter Password Here">


        Age:
            <input class="submissionfield" type="number" required pattern="[0-9]" title="Please enter your age, only numeric characters are allowed " name="age" required placeholder="Select your age &gt; &gt; ">

            Are you Male or Female?
                <input type="radio" name="gender" value="male" checked> Male
                <input type="radio" name="gender" value="female"> Female


            What gender are your dogs?
                <input type="checkbox" name="gender_of_cats[]" value="male" checked> Male &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="checkbox" name="gender_of_cats[]" value="female"> Female &nbsp;&nbsp;&nbsp;&nbsp;


    <div class="registration_form_complete">
        <input id ="registration_buttons" type="submit" value="Submit"> 
    </div>
</form>

3 个答案:

答案 0 :(得分:1)

有几种方法。使用AJAX API调用进行验证允许您在发布表单之前通知用户字段有问题。这是迄今为止用户最友好的选择。

如果您真的想要POST并让服务器一次性完成所有验证,则有2个选项。主要问题是POST 重新加载页面。因此,您需要服务器使用新的表单页面响应POST,并且填写服务器端的验证值(以便用户返回填写的表单。

第二种方法是在POST时将值存储在localstorage中,并在重新加载页面时使用javascript再次加载它们。但是,在这种情况下,您无法直接从服务器获取验证值,因此我推荐此方法。

答案 1 :(得分:0)

你需要Javascript。表单提交后,页面将重新加载,因此默认情况下会丢失任何信息。要存储值,您可以在提交表单之前创建cookie,并将这些值onLoad()加载到字段中。

答案 2 :(得分:0)

你可以尝试

 <input class="submissionfield" type="text" name="name" value="<?php echo $_POST?$_POST["name"]:""; ?>" required pattern="[a-zA-Z\s]+" title="Your name can only contain alphabetic characters" placeholder="Bob Smith">