Adding a custom message to the Zend Framework 2 Callback Validator

I would like to add a special error message to my Callback Validator below (for example, "Postal Code"), how would I do it?

$zip = new \Zend\InputFilter\Input('zip'); $zip->setRequired(false); $zip->getValidatorChain() ->attach(new \Zend\Validator\Callback(function ($value, $context) { if($context['location_type_id'] == \Application\Model\ProjectModel::$LOCATION_TYPE_ID_AT_AN_ADDRESS) { return (isset($value)&&($value!= NULL))? $value: false; } return true; })); 

If you need more information, let me know and I will update. Thanks for your help!

Abor

+4
source share
3 answers

You can do it as follows:

 $callback = new \Zend\Validator\Callback(function ($value) { // Your validation logic } ); $callback->setMessage('Zip Code is required'); $zip = new \Zend\InputFilter\Input('zip'); $zip->setRequired(false); $zip->getValidatorChain()->attach($callback); 
+6
source

Just to throw my two cents, a custom message can also be customized via configuration. I often use this when using a factory approach like this:

 'name' => array( ... 'validators' => array( new \Zend\Validator\Callback( array( 'messages' => array(\Zend\Validator\Callback::INVALID_VALUE => '%value% can only be Foo'), 'callback' => function($value){ return $value == 'Foo'; })) ) ), 

This creates a message like "The bar can only be Foo."

Look carefully at the \Zend\Validator\Callback::INVALID_VALUE key, this is the constant defined in \ Zend \ Validator \ Callback:

 const INVALID_VALUE = 'callbackValue'; 

which is used in this class to set messages used by the validator:

 protected $messageTemplates = array( self::INVALID_VALUE => "The input is not valid", self::INVALID_CALLBACK => "An exception has been raised within the callback", ); 

This means that you can safely use \Zend\Validator\Callback::INVALID_VALUE => 'Custom message'

I'm not sure if this violates the coding principle, someone please correct me if this happens.

+10
source

Thanks to jchampion for his help.

  $zip = new \Zend\InputFilter\Input('zip'); $zip->setRequired(false); $callback = new \Zend\Validator\Callback(function ($value, $context) { if($context['location_type_id'] == \Application\Model\ProjectModel::$LOCATION_TYPE_ID_AT_AN_ADDRESS) { return (isset($value)&&($value!= NULL))? true: false; } return true; }); $callback->setMessage('Zip Code is required'); $zip->getValidatorChain()->attach(new \Zend\Validator\NotEmpty(\Zend\Validator\NotEmpty::NULL)); $zip->getValidatorChain()->attach($callback); 
0
source

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


All Articles