Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom message to Zend Framework 2 Callback Validator

I would like to add a custom error message to my Callback Validator below ("Zip Code is required" for example), how would I go about doing this?

   $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

like image 798
17 revs, 5 users 61% Avatar asked Dec 04 '22 09:12

17 revs, 5 users 61%


1 Answers

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

'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 produces a message like "Bar can only be Foo".

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

const INVALID_VALUE = 'callbackValue';

Which is used in that class to set the 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",
);

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

I'm not sure whether this breaks a coding principle, somebody please correct me if it does.

like image 125
Jaap Moolenaar Avatar answered Apr 23 '23 02:04

Jaap Moolenaar