2
votes

I have an input filter...

    $this->inputFilter->add($factory->createInput([
        'name' => 'reason',
        'required' => true,
        'filters' => [
            [
                'name' => 'StripTags'
            ]
        ],
        'validators' => [
            [
                'name' => 'StringLength',
                'options' => [
                    'min' => 10,
                    'max' => 150
                ]
            ]
        ]
    ]));

When the length is 0, the 'required' error kicks in (appears to use NotEmpty validator.) This gives a very generic message "Value is required and can't be empty."

Since I am showing all errors in list above the form and not next to their input, this is not specific enough.

I am assuming there is a 'messages' key like in the validators array, but I cannot find any documentation on it.

How can I set the message for an empty input?

1

1 Answers

3
votes

I dug through the InputFactory code and found a few things...

continue_if_empty will allow an empty field and still run the validators.

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

You could also add the error_message config. It appears it will always show this error and no others regardless of what happens. This is fine since the only validator is 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,
                ]
            ]
        ]
    ]));

If you still require a "not empty" message, you should be able to add a NotEmpty validator, customize its message, and use continue_if_empty => true config.