2014-02-12 46 views
2

以下是我想要擴展的聯繫表單驗證腳本的代碼。擴展聯繫表單驗證PHP腳本中包含一些錯誤消息

<?php 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $message = $_POST['message']; 
    $from = 'From: DaVv'; 
    $to = '[email protected]'; 
    $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。

+0

您的意思是'客戶端驗證? –

+0

js驗證??或PHP方面驗證? –

+0

js驗證:使用框架。 php驗證:使用'regexp'和reffer到正則表達式庫的電子郵件,電話,字符串等 – JonnieJS

回答

0
<?php 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $message = $_POST['message']; 
    $from = 'From: DaVv'; 
    $to = '[email protected]'; 
    $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>'; 
?> 
0

我不是很確定你想達到什麼,但我假設它是電子郵件服務器端驗證?

如果是這樣,你可以使用下面的PHP代碼片段:

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

對不起你們,我寫以前的錯誤代碼(因爲我在工作)

這是正確的:

<?php 
$name = $_POST['name']; 
$email = $_POST['email']; 
$message = $_POST['message']; 
$from = 'From: domain.com'; 
$to = '[email protected]'; 
$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>'; 
      } 
    } 
?>  

而這個我想補充的電子郵件驗證(服務器端)和味精「U寫錯電郵」或某事像那...但我不想刪除現在包含在聯繫表單中的任何消息。只是想添加有關錯誤電子郵件的信息。

再次感謝您的幫助;)

+0

,我也想顯示一個「錯誤信息」,即使會有例如「不是所有的字段填充」和「錯誤的電子郵件」,我想只顯示這兩個錯誤(這是一個例子) – DaVv