Balagosh Balagosh - 1 month ago 11
PHP Question

Adding Validation to Contact form

I created a Contact form using HTML and PHP.

HTML Code:



<!--Contact Starts -->
<div class="container contactform center">
<h2 class="text-center wowload fadeInUp">Get in touch</h2>
<div class="row wowload fadeInLeftBig">
<div class="col-sm-6 col-sm-offset-3 col-xs-12">
<form action="/assets/bootstrap/php/emailscript.php" method="post">
<input type="text" placeholder="Name" name="Name">
<input type="text" placeholder="Company" name="Company">
<input type="text" placeholder="Email" name="Email">
<input type="text" placeholder="Subject" name="Subject">
<textarea rows="5" placeholder="Message" name="Message"></textarea>
<button type="submit" class="btn btn-primary"><i class="fa fa-paper-plane"></i> Send</button>
</form>

</div>
</div>
</div>
<!--Contact Ends-->





PHP Code:

<?php
if(isset($_POST['Name']))
{
$name=$_POST['Name'] ;
$company=$_POST['Company'] ;
$from=$_POST['Email'] ;
$message=$_POST['Message'] ;
$to="contact@website.com" ;
$subject="Website Contact Form" ;

mail ($to, $subject, $message, "From: " . $name . $company . $email) ;
echo "Sent" ;

}
?>


I want to add a validation to the email filed also make all the other fields mandatory.

Answer

Can try

  1. required in html

    <input .... name="Name" required>
    
  2. empty in PHP

    if (empty($name) || empty($company) || empty($from) ||empty($message)) {
        # empty
        echo "Empty....";
    } else {
        # send mail
        mail ($to, $subject, $message, "From: " . $name . $company . $email) ;
    }
    

Or can use validation or JavaScript too

beware about SQL Injection

Example of contact form validation