2009-06-18 52 views
2

我使用Zend_Validate來驗證某些表單輸入(Zend Framework版本是1.8.2)。出於某種原因,使用Zend_Filter_Input接口描述here不起作用:爲什麼我無法覆蓋默認的驗證錯誤消息?

$data = $_POST; 
$filters = array('*' => array('StringTrim')); 
$validators = array('driverName' => array('NotEmpty','messages' => 'This should override the default message but does not!')); 
$inputFilter = new Zend_Filter_Input($filters,$validators,$data); 
$messages = $inputFilter->getMessages(); 
debug($messages); //show me the variable contents 

輸出debug($messages)

Array 
(
    [driverName] => Array 
     (
      [isEmpty] => You must give a non-empty value for field 'driverName' 
     ) 

) 

不管我做什麼,我不能覆蓋該消息。如果我直接使用驗證,即:

$notEmpty = new Zend_Validate_NotEmpty();  
$notEmpty->setMessage('This WILL override the default validation error message'); 
if (!$notEmpty->isValid($_POST['driverName'])) { 
    $messages = $notEmpty->getMessages(); 
    debug($messages); 
} 

輸出debug($messages)

Array 
(
    [isEmpty] => Please enter your name 
) 

底線。我可以得到驗證器的工作,但沒有Zend_Filter_Input接口驗證方法的好處,我不妨寫我自己的驗證類!

有沒有人有一個線索,爲什麼發生這種情況,以及如何解決它?

它可能是一個錯誤?

回答

5

驗證器數組中的messages鍵必須傳遞一個鍵/值對的數組,其中鍵是驗證消息常量,並且該值是您的自定義錯誤消息。這裏有一個例子:

$validators = array(

     'excerpt' => array(
      'allowEmpty' => true, 
      array('StringLength', 0, Ctrl::getOption('blog/excerpt/length')), 
      'messages' => array(Zend_Validate_StringLength::TOO_LONG => 'The post excerpt must not exceed '.Ctrl::getOption('blog/excerpt/length').' characters.') 
     ), 

    ); 

然而,在你的情況,您收到錯誤消息是從的Zend_Filter_Input的的allowEmpty元命令來了。這不是一個真正的標準驗證器。您可以設置它,如下所示:

$options = array(
    'notEmptyMessage' => "A non-empty value is required for field '%field%'" 
); 

$input = new Zend_Filter_Input($filters, $validators, $data, $options); 

// alternative method: 

$input = new Zend_Filter_Input($filters, $validators, $data); 
$input->setOptions($options); 

如果你需要每場不同的非空的消息,我建議設置allowEmpty => true並添加NotEmpty驗證了自定義消息。

作爲參考,用於NotEmpty驗證正確的消息密鑰是Zend_Validate_NotEmpty::IS_EMPTY

+0

@Jason - 謝謝你的詳細信息及正確答案。 $ options參數釘住了它。完美,再次感謝:) – karim79 2009-06-18 15:56:29

1

消息參數採用的陣列,而不是字符串。試試這個:

$validators = array('driverName' => 
        array('NotEmpty', 
          'messages' => array(
           0 => 'This should override the default message but does not!' 
          ) 
        ) 
      ); 
+0

@Steve - 我已經嘗試過,手冊會讓你相信它的工作原理,但事實上它並不是,但謝謝你的答案nontheless :) – karim79 2009-06-18 15:54:29

0

這是一個錯誤,這是Zend框架的JIRA ...

相關問題