将自定义验证错误消息按元素合并到表单对象中
Posted
技术标签:
【中文标题】将自定义验证错误消息按元素合并到表单对象中【英文标题】:Incorporate custom validation error messages into form object by element 【发布时间】:2018-02-08 21:34:58 【问题描述】:我有以下创建特定文本元素的代码:
$this->add([
'type' => 'text',
'name' => 'newpassword',
'attributes' => [
'id' => 'newpassword',
'class' => 'form-control'
],
'options' => [
'label' => 'Enter New User Password',
],
]);
我有以下代码生成我的输入过滤器定义:
$inputFilter->add([
'name' => 'newpassword',
'required' => true,
'filters' => [
['name' => 'StringTrim'],
['name' => 'StripTags']
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 6,
'max' => 256
],
]
],
]);
我想要完成的是添加我的自定义消息。这是他们在 api 文档中的用法:
$validator = new Zend\Validator\StringLength(array('min' => 8, 'max' => 12));
$validator->setMessages( array(
Zend\Validator\StringLength::TOO_SHORT =>
'The string \'%value%\' is too short',
Zend\Validator\StringLength::TOO_LONG =>
'The string \'%value%\' is too long'
));
如何将我的自定义验证消息合并到我已经编程的代码中?
更新:
我认为这是我会找到成功的地方,但不知道该怎么做:
$inputFilter->get('newpassword')->getValidatorChain()->
【问题讨论】:
【参考方案1】:使用 this-: 它的messageTemplates
来设置自定义消息
$inputFilter->add([
'name' => 'newpassword',
'required' => true,
'filters' => [
['name' => 'StringTrim'],
['name' => 'StripTags']
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 6,
'max' => 256,
'messageTemplates'=>array(
\Zend\Validator\StringLength::TOO_SHORT =>
'The string \'%value%\' is too short',
\Zend\Validator\StringLength::TOO_LONG =>
'The string \'%value%\' is too long'
)
],
]
],
]);
【讨论】:
我认为messageTemplates
应该是messages
,不知道messageTemplates
是否有效。以上是关于将自定义验证错误消息按元素合并到表单对象中的主要内容,如果未能解决你的问题,请参考以下文章