2013-03-28 80 views
3

我正在使用ZF2表單驗證。我必須驗證兩個字段USERNAME和PASSWORD。 一切工作正常,但我喜歡ZF2-需要在特定條件失敗時顯示特定錯誤消息

Please enter username. 
Username can not be less than 3 characters. 

Please enter password. 
Password can not be less than 6 characters. 

獲取消息。如果用戶沒有輸入任何值,則僅此消息應顯示

Please enter username.  
Please enter password. 

我不想做顯示所有的錯誤信息一個失敗的領域。

在此先感謝。

回答

6

我得到了答案: 爲了打破驗證鏈ZF2,我們必須使用

'break_chain_on_failure'=>真

$this->add(
    array(
     'name'  => 'usernmae', 
     'required' => true, 
     'filters' => array(
      array('name' => 'Zend\Filter\StringTrim') 
     ), 
     'validators' => array(
          array('name' => 'NotEmpty', 
          'options' => array('encoding' => 'UTF-8', 
           'messages' => array(
            NotEmpty::IS_EMPTY => 'Please enter username')), 
          'break_chain_on_failure' => true), 
      array(
       'name' => 'Zend\Validator\StringLength', 
       'options' => array(
        'encoding' => 'UTF-8', 
        'min'  => 3, 
        'max'  => 30, 
        'messages' => array(
            StringLength::TOO_LONG => 'Username can not be more than 30 characters long', 
            StringLength::TOO_SHORT => 'Username can not be less than 3 characters.') 
       ), 
       'break_chain_on_failure' => true 
      ) 
     ) 
    ) 
); 

我的博客:http://programming-tips.in

+0

這個萬歲'break_chain_on_failure'! – David 2016-02-08 20:44:21

1

Zend_Validate允許您在某些驗證失敗時打斷驗證器鏈。在這種情況下,addValidator()函數$ breakChainOnFailure的第二個參數應該爲TRUE。

$validatorChain = new Zend_Validate();  
$validatorChain->addValidator(new Zend_Validate_NotEmpty(), TRUE) 
       ->addValidator(new Zend_Validate_StringLength(6, 12)); 
+0

感謝您的回覆@Zavg ...但我需要Zend Framework 2 – Arvind 2013-03-28 10:06:54

0

您也可以設置'error_message'鍵,例如:

'email' => [ 
       'required' => true, 
       'error_message' => 'Incorrect email address ', 
       'filters' => [ 
        [ 
         'name' => 'StripTags', 
        ], 
        [ 
         'name' => 'StringToLower', 
        ] 
       ], 
       'validators' => [ 
        [ 
         'name' => 'EmailAddress', 
         'break_chain_on_failure' => true 
        ] 
       ] 
      ], 
相關問題