什么是在不清除表单的情况下验证表单的最佳方法?

时间:2016-02-01 20:28:12

标签: php html forms

我有一些html表单,我用php验证完整性。我遇到的问题是,当一个必填表格未填写时,填写的表格将被清除。

HTML

<p>Email: <span class="required">* <?php echo $EmailErr;?></span><input type="text" name="Email" placeholder="Email" /></p>
<p>Comments: =input type="text" name="Comments" maxlength="75" placeholder="Comments"/></p>

这是PHP

 if (empty($_POST["Email"])) {
   $EmailErr = "";
   } else {
   $Email = validateEmail($_POST["Email"]);
   }        

   if (empty($_POST["Comments"])) {
   $Comments = "";
   } else {
   $Comments = test_input($_POST["Comments"]);
   }  

问题仍然存在,如何防止其他表格在提交后被清除?

2 个答案:

答案 0 :(得分:1)

您应该进行客户端验证,以便保留表单上的值。

据说你还应该进行服务器验证。

有不同的方法,使用javascript / jquery甚至只是将required属性添加到您的代码中,例如:

<input type="text" name="Email" placeholder="Email" required/>

for javascript:

http://www.w3schools.com/js/js_validation.asp

对于jquery,这是一个很好的插件:

http://jqueryvalidation.org/

答案 1 :(得分:0)

<p>
    Email: <span class="required">*<?php echo $EmailErr; ?></span>
    <input type="text" name="Email" placeholder="Email" value="<?php echo!empty($_POST['Email']) ? htmlspecialchars($_POST['Email']) : '' ?>"/>
</p>
<p>
    Comments: <textarea name="Comments" maxlength="75" placeholder="Comments"><?php echo!empty($_POST['Comments']) ? htmlspecialchars($_POST['Comments']) : '' ?></textarea>
</p>
相关问题