如何获取FILTER_VALIDATE_EMAIL返回的错误

时间:2013-08-01 16:25:17

标签: php arrays validation email filter

我目前正在使用php。我当前的表单应该为电子邮件模板生成一些标准。它有一个To,CC和BCC字段。我目前的“To”代码运行正常。然后我想一次验证多封电子邮件。例如,如果有人输入了example@example.com,test @ test.com等,我希望它能够检查每一个。由于某种原因,它是一个错误。下面是我目前的PHP。我想知道是否有一种方法可以看出错误是什么。有什么想法或建议吗?

$errTo = $_POST['To'];
$errCC = $_POST['CC'];
$errBCC = $_POST['BCC'];
function died() 
{
$error = false;
return $error;
}

我遇到了我的问题

if($_POST['submit'] == 'Submit')
{
if(filter_var($errTo, FILTER_VALIDATE_EMAIL))
{
    if(isset($errCC))
    {
        $errCC = explode(",", $errCC);
        $count = count($errCC);
        for($i=0; $i<$count; ++$i)
        {
            $errCC[$i] = str_replace(" ", "",$errCC[$i]);
            echo $errCC[$i];
            if(!filter_var($errCC[$i], FILTER_VALIDATE_EMAIL))
            {
                $error = died();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

此功能在失败时始终返回false,因此您需要自己处理原因。原因始终是它不是有效的电子邮件地址。它不会告诉你This email is missing a @ symbol

$errors = array();
if($_POST['submit'] == 'Submit')
{
    // Check the to field and add it to the error array if its wrong
    if(!filter_var($errTo, FILTER_VALIDATE_EMAIL))
    {
       $errors[] = $errTo;
    }

    if(isset($errCC))
    {
      $errCC = explode(",", $errCC);
      $count = count($errCC);
      for($i=0; $i<$count; ++$i)
      {
          $errCC[$i] = str_replace(" ", "",$errCC[$i]);
          echo $errCC[$i];
          if(!filter_var($errCC[$i], FILTER_VALIDATE_EMAIL))
          {
              // Add to our array the invalid emails
              $errors[] = $errCC[$i];
          }
      }
    }

    // Check if we have any invalid emails    
    if(count($errors))
    {
      // Display each email, remember to strip out 'badness' if you are outputting user variable to the browser
      foreach($errors as $err)
      {
          echo strip_tags($err) . " is not an email address<br />";
      }
    }
}