我有一个输入过滤器......
$this->inputFilter->add($factory->createInput([
'name' => 'reason',
'required' => true,
'filters' => [
[
'name' => 'StripTags'
]
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 10,
'max' => 150
]
]
]
]));
当长度为0时,“必需”错误开始(似乎使用NotEmpty验证器。)这给出了一个非常通用的消息“值是必需的,不能为空。”
由于我在表单上方显示列表中的所有错误而不是其输入旁边的错误,因此这不够具体。
我假设在验证器数组中有一个'messages'键,但我找不到任何文档。
如何为空输入设置消息?
答案 0 :(得分:3)
我挖掘了InputFactory代码并找到了一些东西......
continue_if_empty将允许空字段并仍然运行验证器。
$this->inputFilter->add($factory->createInput([
'name' => 'reason',
'continue_if_empty' => true,
'filters' => [
[
'name' => 'StripTags'
]
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 10,
'max' => 150,
'messages' => [
\Zend\Validator\StringLength::TOO_SHORT => 'The reason must be greater than %min% characters.',
\Zend\Validator\StringLength::TOO_LONG => 'The reason must be less than %max% characters.'
]
]
]
]
]));
您还可以添加error_message配置。它似乎总会显示此错误,而不管发生什么事情都没有。这很好,因为唯一的验证器是StringLength。
$this->inputFilter->add($factory->createInput([
'name' => 'reason',
'error_message' => 'The reason must be between 10 and 150 characters in length.',
'filters' => [
[
'name' => 'StripTags'
]
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 10,
'max' => 150,
]
]
]
]));
如果您仍然需要“非空”消息,则应该能够添加NotEmpty验证器,自定义其消息,并使用continue_if_empty => true config。