2012-03-01 107 views
1

我只是無法弄清楚如何在Zend_Form對象中設置自定義驗證器消息。這是一個示例代碼。無法在Zend_Form中設置自定義驗證器消息

$this->addElement('password', 'password', array(
     'label'  => 'Password', 
     'decorators' => array('ViewHelper'), 
     'filters' => array('StringTrim'), 
     'validators' => array(
      array('Digits', false, array('messages' => array('notDigits' => 'Only digits are allowed here'))) 
     ), 
     'required' => true 

    )); 

當我試圖驗證輸入無效數據的消息的形式說「notDigits」出現。我試圖將'notDigits'改爲Zend_Validate_Digits :: NOT_DIGITS,但它仍然無法按預期工作。

任何幫助,非常感謝!

回答

2

我發現我的錯誤。我收到'notDigits'消息,因爲在控制器中我使用$ form-> getErrors()方法而不是$ form-> getMessages()。第一個只返回錯誤代碼,沒有消息。

1

用於設置自定義消息的語法是正確的。在您發佈的代碼示例中,該元素的唯一裝飾器是ViewHelper,因此不會顯示錯誤消息。

如果您想查看錯誤消息,請至少添加Errors修飾符。試試這個:

$this->addElement('password', 'code', array(
    'label'  => 'Code', 
    'decorators' => array('ViewHelper', 'Errors'), 
    'filters' => array('StringTrim'), 
    'validators' => array(
     array('Digits', false, 
      array('messages' => array('notDigits' => 'Only digits are allowed here'))) 
    ), 
    'required' => true 
); 

唯一的變化是將Errors裝飾器添加到堆棧。

+0

謝謝你的回覆drew010。我不使用Errors裝飾器,因爲我使用$ form-> getErrors()方法捕獲控制器中的錯誤,所以我可以將它們顯示在單獨的DIV中。錯誤顯示正確,但翻譯不適用。 – stefan 2012-03-02 07:06:39

0

試試這個驗證器語法。

$this->addElement("text", "fullname", array(
         'label' => 'Your Full Name: ', 
         'required' => 'true', 
         'validators' => array(
          array('validator' => 'StringLength', 'options' => array('min'=>5, 'max'=>250, 'messages' => array('stringLengthTooShort' => 'The name is too short.'))) 
         ), 
         'filters' => array('StringTrim'), 
         'decorators' => array("signup") 
        ));