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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With