我如何检查电子邮件是否有效

时间:2013-10-04 18:35:03

标签: php validation

如何验证电子邮件并为现有代码添加淡入效果?

<?php
if ($_POST['submit']) { 
if ($name != '' && $email != '') { 
if (mail ($to, $subject, $body, $from)) {    
echo '<div style="border: 1px solid #00EE00; padding: 10px;"><p>Your message has been sent to our Customer Care Team.</p></div>';    } else {    
echo ' <div style="border: 1px solid #FF030D; padding: 10px;"><p>Something went wrong, go back and try again!</p></div> ';   }  } 
else if ($_POST['submit'] ) {    
echo '<div style="border: 1px solid #FF030D; padding: 10px;"> <p>You need to fill in all required fields!!</p></div>'; } }
?>

1 个答案:

答案 0 :(得分:3)

您可以使用FILTER_VALIDATE_EMAIL

来验证电子邮件地址
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     echo "E-mail is not valid";
} else {
      // your code
}

您可以在代码中实现它,例如......

<?php
if ($_POST['submit']) { 
    if ($name != '' && $email != '') { 
        if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
            if (mail ($to, $subject, $body, $from)) {    
                echo '<div style="border: 1px solid #00EE00; padding: 10px;"><p>Your message has been sent to our Customer Care Team.</p></div>';
            } else {    
                echo ' <div style="border: 1px solid #FF030D; padding: 10px;"><p>Something went wrong, go back and try again!</p></div> ';
            }
        }
        else
        {
            echo '<div style="border: 1px solid #FF030D; padding: 10px;"> <p>Invalid Email Address</p></div>';
        }
    } 
    else{    
        echo '<div style="border: 1px solid #FF030D; padding: 10px;"> <p>You need to fill in all required fields!!</p></div>'; 
    }
}
?>