向联系人添加电子邮件验证表单


Adding an Email Validation to Contact form

我使用HTML和PHP创建了一个Contact表单。

我设法在HTML中使用" required "使字段成为强制性的。然而,现在,即使我添加任何东西在电子邮件字段,提交按钮工作。

我更喜欢用HTML而不是PHP来做这个。

  • 我的编码技能非常有限。
HTML代码:

<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代码:

<?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" ;
}
?>

我想只提交有效的电子邮件表单(email@domain.TLD)

email:

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

,其他输入字段使用

if(!isset($_POST['fieldName'])) {
    // throw exception or return error
}

在您的PHP代码中:

<?php
if(isset($_POST['Email']) && $_POST['Email']!='')
{
    $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" ;
  }
  else
  {
    echo "Please insert email address."; 
  }
?>

可以试试

  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) ;
    }
    

或者也可以使用验证或JavaScript

小心SQL注入

联系人表单验证示例