我有一个表单,并且 for m 的操作是同一页。 我正在尝试:
- 在成功提交表单时显示感谢信息
- 在检测到错误的字段旁边显示错误消息
- 以上所有内容必须显示在同一页面中。
我的代码是:
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
else {
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
?>
我限制了验证,只显示了这个问题的第一部分。
当我提交此表单时,如果没有任何错误,我将收到消息谢谢,我们已收到您的反馈 这很好,并且按预期工作。
当存在错误/字段客人姓名 为空时,我在表单提交过程中收到消息错误! 请检查以下有错误的字段。错误提示为红色。 这也很好。
但是当我收到上述消息时,我的表单就消失了。为什么? 我还想在字段旁边显示请输入您的姓名!。
最佳答案
试试下面的代码。我已经删除了 else 部分并设置了 true/false 标志以检查是否有效。
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
$chkValidate = "true";
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
$chkValidate = "false";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';
$chkValidate = "false";
}
if($chkValidate == "true"){
echo 'Thanks, We have received your feed back';
}
}
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?php if(!empty($errors) && $chkValidate != "false") { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
?>
关于php - 为什么这个验证码没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29449350/