我想在下面的Callback Validator中添加一条自定义错误消息(例如“需要邮政编码”),我该怎么做?
$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;
}));
如果您需要更多信息,请告诉我,我会更新。 谢谢你的帮助!
ABOR
答案 0 :(得分:10)
只需投入两分钱,也可以通过配置设置自定义消息。我经常在使用像这样的工厂类型方法时使用它:
'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';
}))
)
),
这会产生一条消息,例如“Bar只能是Foo”。
仔细查看\Zend\Validator\Callback::INVALID_VALUE
键,这是\ Zend \ Validator \ Callback中定义的常量:
const INVALID_VALUE = 'callbackValue';
在该类中使用哪个来设置验证器使用的消息:
protected $messageTemplates = array(
self::INVALID_VALUE => "The input is not valid",
self::INVALID_CALLBACK => "An exception has been raised within the callback",
);
这意味着您可以安全地使用\Zend\Validator\Callback::INVALID_VALUE => 'Custom message'
我不确定这是否打破了编码原则,有人请纠正我,如果确实如此。
答案 1 :(得分:6)
你可以这样做:
$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);
答案 2 :(得分:0)
感谢jchampion的帮助。
$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);