ZF2 - it is necessary to display a specific error message when a certain state fails

I am using form validation ZF2. I have to check the two fields USERNAME and PASSWORD. everything is working fine, but I get a message like

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

If the user does not enter any value, then only this message should display

 Please enter username. Please enter password. 

I do not want to display all error messages in the field on error.

Thanks in advance.

+3
source share
3 answers

I got the answer: To break the validation chain in ZF2, we must use

'break_chain_on_failure' => true

 $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 ) ) ) ); 

My blog: http://programming-tips.in

+6
source

Zend_Validate allows you to break the chain of validators if certain validations fail. The second parameter to the addValidator () $ breakChainOnFailure function should be TRUE in this case.

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

You can also set the key "error_message", for example:

 'email' => [ 'required' => true, 'error_message' => 'Incorrect email address ', 'filters' => [ [ 'name' => 'StripTags', ], [ 'name' => 'StringToLower', ] ], 'validators' => [ [ 'name' => 'EmailAddress', 'break_chain_on_failure' => true ] ] ], 
0
source

Source: https://habr.com/ru/post/949746/


All Articles