Abo*_*ove 4 validation message callback zend-framework2
我想在下面的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;
}));
Run Code Online (Sandbox Code Playgroud)
如果您需要更多信息,请告诉我,我会更新.谢谢你的帮助!
ABOR
Jaa*_*aar 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';
}))
)
),
Run Code Online (Sandbox Code Playgroud)
这会产生一条消息,例如"Bar只能是Foo".
仔细查看\Zend\Validator\Callback::INVALID_VALUE键,这是\ Zend\Validator\Callback中定义的常量:
const INVALID_VALUE = 'callbackValue';
Run Code Online (Sandbox Code Playgroud)
在该类中使用哪个来设置验证器使用的消息:
protected $messageTemplates = array(
self::INVALID_VALUE => "The input is not valid",
self::INVALID_CALLBACK => "An exception has been raised within the callback",
);
Run Code Online (Sandbox Code Playgroud)
这意味着您可以放心使用 \Zend\Validator\Callback::INVALID_VALUE => 'Custom message'
我不确定这是否打破了编码原则,有人请纠正我,如果确实如此.
小智 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5867 次 |
| 最近记录: |