我有一个输入姓名和电子邮件的表格。我想为每个输入都有一个专用的错误消息 - 如果没有写名字,它会说 fx "please write your name!"
,如果电子邮件丢失或无效,它会回显"wrong mail - try again!"
目前,我只有 1 条错误消息会在两种情况下都回显。如何为每个输入分配专用的错误消息?
继承人的代码:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = '#@gmail.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
<article class="kontakt">
<?php if($_POST['contactname'] != '') { //echo when a name was entered ?>
<!--<p> Hello </p>-->
<?php $name = strip_tags(trim($_POST['contactname']));
echo $name;
} ?>
</article>
<article class="kontakt">
<?php if(isset($hasError)) { // THIS PART IS ECHOED IN BOTH SITUATIONS - should only apply for error in e-mail?>
<p class="error"> Your mail is <span style="color: orange"> not correct</span> - try again! </p>
<?php } ?>
<?php if($_POST['email'] != '') { // echo when a valid mail was entered ?>
<p> Hello </p>
<?php $name = strip_tags(trim($_POST['email']));
echo $email;
} ?>
</article>
<article class="kontakt">
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p> Your message is sent !</p>
<?php } ?>
</article>
}
?>