fanir miah tarafdar fanir miah tarafdar - 4 months ago 8
PHP Question

Why valdation error for message field doesn't show

I am creating a contact form for a website with server side validation, the validation works for the name and email but it doesn't work for message field. So users can send message with just filling in name and email field. Code is below:

PHP

<?php

if($_POST['submit']){
if(!$_POST['name']){
$error= "<br/>-Please enter your name" ;

}

if(!$_POST['email']){
$error.= "<br/>-Please enter your email" ;

}

if(!$_POST['message']){
$error.= "<br/>-Please enter message" ;

}

if ($error){
$result= "Whoops, error: $error";

}
else{
mail('mahdi.mashrafi@yahoo.com', "Contact message", "Name: ".$_POST['name']." Email: ".$_POST['email']."
Email: ".$_POST['name']."
Message : ".$_POST['message']);

{
$result= "Thankyou, Ill be in touch shortly";
}
}


}


?>


HTML

<section id = "contact">
<div class = "container">
<div class = "row">
<div class = "col-md-6 col-md-offset-3">
<h1>Contact Form</h1>
<?php echo $result; ?>
<p>Send a form a message via form below </p>
<form method = "post" role = "form">
<div class = "form-group">
<input type = "text" name = "name" class = "form-control" placeholer = "Your name" value = "<?php echo $_POST['name'];?>" >
</div>

<div class = "form-group">
<input type = "email" name = "email" class = "form-control" placeholer = "Your email" value ="<?php echo $_POST['email'];?>">
</div>

<div class = "form-group">
<textarea name = "message" rows = "5" class = "form-control" placeholder = "message"><?php echo $_POST['message']; ?> </textarea>
</div>

<input type = "submit" name = "submit" class = "btn btn-secondary" value = "send message"/>
</form>

</div>

</div >


</div>
</section>


How can I make the message field required before details can be sent.

Answer

Try this I think this should be work..

if (trim($_POST['message']) == "")
{
   $error.= "<br/>-Please enter message";
}