Incorporate custom validation error messages into form object by element

74 views Asked by At

I have the following code which creates a specific text element:

       $this->add([           
            'type'  => 'text',
            'name' => 'newpassword',
            'attributes' => [
                'id' => 'newpassword',
                'class' => 'form-control'
            ],
            'options' => [
                'label' => 'Enter New User Password',
            ],
        ]);

And I have the following code which produces my input filter definitions:

            $inputFilter->add([
                    'name'     => 'newpassword',
                    'required' => true,
                    'filters'  => [
                        ['name' => 'StringTrim'],
                        ['name' => 'StripTags']                 
                    ],
                    'validators' => [
                        [
                            'name'    => 'StringLength',
                            'options' => [
                                'min' => 6,
                                'max' => 256
                            ],
                        ]                   
                    ],
            ]);       

What I want to accomplish is adding my custom messages. Here's the way they have it in the api documentation:

$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'
));

How do I incorporate my custom validation messages into my already programmed code?

UPDATE:

I think this is where i will find success, but not sure how to do it:

$inputFilter->get('newpassword')->getValidatorChain()->
1

There are 1 answers

1
Gautam Rai On

Use this-: its messageTemplates to set custom message

$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'
                        )
                    ],
                ]
            ],
        ]);