将自定义验证错误消息按元素合并到表单中

时间:2017-08-31 03:35:14

标签: zend-framework2 zend-form zend-form-element zend-framework3 zend-form2

我有以下代码创建一个特定的文本元素:

       $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 个答案:

答案 0 :(得分:0)

使用此 - :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'
                        )
                    ],
                ]
            ],
        ]);