Saturday, 7 September 2013

echo an error message for each input in form

echo an error message for each input in form

i have a form with input for name and e-mail. I would like to have a
dedicated error-message for each input - fx if no name is written it will
say "please write your name!" and if the e-mail is missing or not valid it
echoes "wrong mail - try again!"
At the moment I have only 1 error-message that will echo for both
situations. How can i assign an dedicated error-message for each of the
inputs?
Heres the code:
<?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>
}
?>

No comments:

Post a Comment