我有一些html表单,我用php验证完整性。我遇到的问题是,当一个必需的表格没有填写时,填写的表格会被清除。
该目录
<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"]);
}
问题仍然存在,我如何防止其他表格在提交时被清除?
您应该执行客户端验证以保留表单上的值。
话虽如此,您仍然应该进行服务器验证。
有不同的方法可以做到这一点,使用 javascript/jquery,甚至简单地将required
属性添加到您的标签中,例如:
<input type="text" name="Email" placeholder="Email" required/>
对于 JavaScript:
http://www.w3schools.com/js/js_validation.asp
对于jquery,这里有一个很好的插件:
http://jqueryvalidation.org/
<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>