Balagosh Balagosh - 1 month ago 8
PHP Question

Adding an Email Validation to Contact form

I created a Contact form using HTML and PHP.

i managed to make the fields mandatory using "reguired" in the HTML.
however, right now even when i add anything in the Email fild, the submit button works.

i prefer to do this with HTML rather than PHP.


  • my skills in coding is very limited.



HTML Code:



<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" required >
<input type="text" placeholder="Company" name="Company" required >
<input type="text" placeholder="Email" name="Email" required >
<input type="text" placeholder="Subject" name="Subject" required >
<textarea rows="5" placeholder="Message" name="Message" required ></textarea>
<button type="submit" class="btn btn-primary"><i class="fa fa-paper-plane"></i> Send</button>
</form>

</div>
</div>
</div>





PHP Code:



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

mail ($to, $subject, $message, "From: " . $from . $name . $company ) ;

echo "Sent" ;

}
?>





I want to submit only with valid email form (email@domain.TLD)

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

Comments