2012-11-16 24 views
1
$app->post('/', function() use ($app) { 

    $email = new Input('email'); 
    $email->getValidatorChain() 
      ->addValidator(new Validator\EmailAddress()); 

    $password = new Input('name'); 
    $password->getValidatorChain() 
      ->addValidator(new Validator\StringLength(1)); 

    $inputFilter = new InputFilter(); 
    $inputFilter->add($email) 
       ->add($password) 
       ->setData($_POST); 

    if ($inputFilter->isValid()) { 

     // do stuff 

     $app->redirect('/'); 

    } else { 

     $field_errors = array(); 

     foreach ($inputFilter->getInvalidInput() as $field => $error) { 
      foreach ($error->getMessages() as $message) { 
       $field_errors[] = str_replace('Value', ucfirst($field), $message); 
      } 
     } 

     $app->render('index.php', array('field_errors' => $field_errors)); 

    } 
}); 

我目前有上面的代碼使用Slim Framework和使用Zend InputFilter。但是,我想檢索錯誤消息。我不斷收到「價值......」所以我做了他們str_replace得到Email is not a valid email象下面這樣:檢索來自Zend的錯誤消息InputFilter

 $field_errors = array(); 

     foreach ($inputFilter->getInvalidInput() as $field => $error) { 
      foreach ($error->getMessages() as $message) { 
       $field_errors[] = str_replace('Value', ucfirst($field), $message); 
      } 
     } 

這是從Zend的輸入過濾得到錯誤信息以正確的方式或者是有什麼事嗎?

+0

是什麼問題? –

+0

我只是在想如果有更好的方法,因爲這是我第一次使用這個組件。 –

回答

4

你只需要調用$ inputFilter->的getMessages()來得到一個鍵陣列回:

array(
    'input' -> 'message', 
    'inputtwo' => 'anothermessage', 
); 

這個內部使用getInvalidInput()對你那麼有沒有必要有這些嵌套的foreach循環,一個單個調用getMessages()應該沒問題。