使用一些错误消息扩展联系表单验证PHP脚本

时间:2014-02-12 09:54:46

标签: php forms validation contact

以下是我想要扩展的联系表单验证脚本的代码。

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: DaVv'; 
    $to = 'mail@mail.com'; 
    $subject = 'The topic';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if ($_POST['submit'] {               
        if (mail ($to, $subject, $body, $from)) { 
            echo '<p>Your message has been sent!</p>';
        } else { 
            echo '<p>Something went wrong, go back and try again!</p>'; 
        } 
    } else if ($_POST['submit'] {
        echo '<p>You answered the anti-spam question incorrectly!</p>';
    }
?>

我想为用户添加一条关于电子邮件的消息,例如:“请输入有效的电子邮件地址。”例如,当他们不写“@”时。我知道这包含在html 5中,但我想用HTML5制作这个。

4 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

我不确定你想要实现什么,但我假设它是服务器端验证的电子邮件地址?

如果是这样,您可以使用以下PHP代码段:

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // The user supplied an invalid e-mailaddress
}

答案 2 :(得分:0)

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $from = 'From: DaVv'; 
    $to = 'mail@mail.com'; 
    $subject = 'The topic';

    $body = "From: $name\n E-Mail: $email\n Message:\n $message";

    if(isset($_POST['submit']))
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) !== false)
        {               
            if(mail ($to, $subject, $body, $from))
                echo '<p>Your message has been sent!</p>';
            else
                echo '<p>Something went wrong, go back and try again!</p>'; 
        }
        else
            echo '<p>Wrong Email</p>';

    }
    else if(!isset($_POST['submit']))
        echo '<p>You answered the anti-spam question incorrectly!</p>';
?>

答案 3 :(得分:0)

抱歉,我以前写过错误的代码(因为我在工作)

这是正确的:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: domain.com'; 
$to = 'dawid@main.com'; 
$subject = 'Message from domain.com';

$body = "From: $name\n E-Mail: $email\n Message:\n $message";

if ($_POST['submit']) {
   if ($name != '' && $email != '') {                
      if (mail ($to, $subject, $body, $from)) { 
         echo '<p class="msg">Your message has been sent!</p>';
      } else { 
         echo '<p class="msg">Something went wrong, go back and try again!</p>'; 
      } 
             } else {
                 echo '<p class="msg">You need to fill in all required fields!!</p>';
             }
  }
?>       

对此我想添加电子邮件验证(SERVER SIDE)和msg“你写错了电子邮件”或者......就像那样......但我不想删除现在包含在联系表单中的任何消息。只想添加有关错误电子邮件的信息。

再次感谢您的帮助;)