1

I have setup a form along with filters and validators which seem to work correctly.

However, I can not seem to get custom error messages to work. So far I have tried.

$inputFilter->add(array(
            'name'     => 'message',
            'required' => TRUE,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name'    => 'NotEmpty',
                    'messages'  => array(
                        NotEmpty::IS_EMPTY => "You must specify your message",
                    ),
                ),
            ),
        ));

All I get is the standard validation error message 'Value is required and can't be empty'

Please can someone point me in the right direction, many thanks.

Garry
  • 1,455
  • 1
  • 15
  • 34

1 Answers1

3

You need to put your messages stack into options top key in validator configuration like below:

Wrong:

'validators' => array(
    array(
        'name'    => 'NotEmpty',
        'messages'  => array(
            NotEmpty::IS_EMPTY => "You must specify your message",
        ),
    ),
),

Correct:

'validators' => array(
    array(
        'name'    => 'NotEmpty',
        'options' => array(
            'messages'  => array(
                NotEmpty::IS_EMPTY => "You must specify your message",
            ),
        ),
    ),
),
edigu
  • 9,878
  • 5
  • 57
  • 80
  • I think the correct key is `messageTemplates`. `messages` contains the errors that have occurred already, whereas `messageTemplates` sets the template to use when the `error` method is called with a specific error type. ([See implementation of AbstractValidator::createMessage](https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/AbstractValidator.php#L285)) – Adam Lundrigan Jan 27 '15 at 01:06
  • This is interesting. Your argument seems right. I just traced the flow down to `error()` and `createMessage()` steps inside the AbstractValidator can't figure out how its really works. I never use the `messageTemplates` key before. – edigu Jan 27 '15 at 10:32
  • Thank you @foozy your answer worked fine, placing messages under options done the trick. – Garry Jan 27 '15 at 17:25