我在使用 PHP 进行 html 输入验证时遇到一些问题。验证本身正在发挥作用。我有两个输入:姓名和办公室。 如果我在名称输入上输入了值,但没有将值输入到办公室输入并单击提交按钮,则办公室输入上的验证有效,但它会清除/清空我在名称输入上输入的数据
我在这里做错了什么?
这是我的 PHP 验证:
if (isset($_POST['submit'])){
$signatory_name = $_POST['sig_name'];
$signtory_position = $_POST['sig_position'];
if (!$_POST['sig_name']) {
$errname='<div class="alert alert-danger">Sorry there was an error: Please Enter Your Name</div>';
}
if (!$_POST['sig_office']) {
$erroffice='<div class="alert alert-danger">Sorry there was an error: Please Enter Your office</div>';
}
}
这是我的 html 代码
<form action="signatory.php" method="Post" role="form">
<input class="form-control " id="signatoryname" name="sig_name" placeholder="Name:" >
<input class="form-control " id="signatoryoffice" name="sig_office" placeholder="Office:">
</form>
最佳答案
目前还不清楚你正在做什么或试图做什么,但这是我的尝试:
首先:您应该知道 if (!$_POST['sig_name']) {
表示如果分配的值为 FALSE,您可能需要重新考虑这一点并使用 empty()
相反。
验证输入后,您需要使用提交的值重新填充表单 - 这是一个示例:
<?php
$errname = "";
$erroffice= "";
if (!empty($_POST)) { // Only if there are POST values attached.
$signatory_name = $_POST['sig_name'];
$signtory_position = $_POST['sig_position'];
if (empty($_POST['sig_name'])) {
$errname='<div class="alert alert-danger">Sorry there was an error: Please Enter youre Name</div>';
}
if (empty($_POST['sig_office'])) {
$erroffice='<div class="alert alert-danger">Sorry there was an error: Please Enter youre office</div>';
}
if (empty($errname) && empty($erroffice)) {
//Do whatever you need with the validated inputs...
} else {
//Expose the alerts:
echo $errname.$erroffice;
}
}
?>
<form method="POST" role="form">
<input class="form-control" id="signatoryname" name="sig_name" value="<?php echo (isset($_POST['sig_name']))?$_POST['sig_name']:""; ?>" placeholder="Name:" />
<input class="form-control" id="signatoryoffice" name="sig_office" value="<?php echo (isset($_POST['sig_office']))?$_POST['sig_office']:""; ?>" placeholder="Office:" />
<!-- rest of your form and buttons -->
</form>
关于php 验证从 html 输入中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990212/