PHP 表单必填字段错误消息


PHP form required field error message

好吧,我对PHP一无所知。我是新手,我设法根据自己的需要调整代码,但有些事情我就是无法完成。我有这个联系表格,PHP看起来像这样:

<?php
/* Set e-mail recipient */
$myemail  = "";
/* Check all form inputs using check_input function */
$naam = check_input($_POST['naam'], "Vul uw naam in");
$bedrijf  = check_input($_POST['bedrijf']);
$email  = check_input($_POST['email'], "Vul uw emailadres in");
$telefoonnummer  = check_input($_POST['telefoonnummer']);
$onderwerp = check_input($_POST['onderwerp'], "Vul een onderwerp in");
$bericht = check_input($_POST['bericht'], "Stel een vraag of plaats een opmerking");
/* If e-mail is not valid show error message */
if (!preg_match("/(['w'-]+'@['w'-]+'.['w'-]+)/", $email))
{
show_error("Vul een geldig e-mailadres in");
}
/* Let's prepare the message for the e-mail */
$message = "Beste,
Een bezoeker heeft een bericht gestuurd:
Naam: $naam
E-mail: $email
Onderwerp: $onderwerp
Bericht:
$bericht
Met vriendelijke groet,
$naam
";
/* Send the message using mail() function */
mail($myemail, $onderwerp, $message);
/* Redirect visitor to the thank you page */
header('Location: thanks.htm');
exit();
/* Functions we used*/ 
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
    show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>

表单有四个必填字段$naam、$email、$onderwerp和$bericht。单击提交按钮后,其中任何一个都没有填写,它会给出错误。到目前为止一切顺利,但它在新窗口中发布了错误,覆盖了 contacform。我希望错误消息显示在表单本身上。我只是不知道该怎么做,我在网上找不到可以在代码中实现的这个问题的好答案。

你们谁能对此

有所了解?

您需要将 HTML 表单发布回自身。然后在表单页面的顶部,您需要一个 if 语句来执行如下检查:

if(isset($_POST['submit'])) {
 //do validation
 //$errorMessage = "whatever message you want to show the user"
 if ($errors == 0){
  /* Redirect visitor to the thank you page */
  header('Location: thanks.htm');
  exit();
 }
}

显示表单时:

if(isset($errorMessage))
  print $errorMessage;

您可能希望进行以下更改:

alert(<?php echo $myError; ?>);

<?php echo $myError; ?>