Can't set custom validator messages in Zend_Fo

2019-05-31 23:04发布

I just can't figure it out how to set custom validator messages in Zend_Form object. Here is an example code.

$this->addElement('password', 'password', array(
        'label'      => 'Password',
        'decorators' => array('ViewHelper'),
        'filters'    => array('StringTrim'),
        'validators' => array(
            array('Digits', false, array('messages' => array('notDigits' => 'Only digits are allowed here')))
        ),
        'required'   => true

    ));

When I try to validate the form entering invalid data a message saying "notDigits" appear. I tried to change 'notDigits' to Zend_Validate_Digits::NOT_DIGITS, but it still doesn't work as expected.

Any help is greatly appreciated!

3条回答
走好不送
2楼-- · 2019-05-31 23:20

I found my error. I was recieving the 'notDigits' message, because in the controller I used $form->getErrors() method instead of $form->getMessages(). The first one returns only the error codes, without the messages.

查看更多
闹够了就滚
3楼-- · 2019-05-31 23:30

Your syntax for setting the custom message is correct. In the code example you posted, the only decorator for that element is ViewHelper so the error message will not be displayed.

At the very least, add the Errors decorator if you want to see the error message. Try this:

$this->addElement('password', 'code', array(
    'label'      => 'Code',
    'decorators' => array('ViewHelper', 'Errors'),
    'filters'    => array('StringTrim'),
    'validators' => array(
        array('Digits', false,
            array('messages' => array('notDigits' => 'Only digits are allowed here')))
    ),
    'required'   => true
);

The only change was adding the Errors decorator to the stack.

查看更多
虎瘦雄心在
4楼-- · 2019-05-31 23:41

Try this validator syntax.

$this->addElement("text", "fullname", array(
                        'label' => 'Your Full Name: ',
                        'required' => 'true',
                        'validators' => array(
                            array('validator' => 'StringLength', 'options' => array('min'=>5, 'max'=>250, 'messages' => array('stringLengthTooShort' => 'The name is too short.'))) 
                        ),
                        'filters' => array('StringTrim'),
                        'decorators' => array("signup")
                    ));
查看更多
登录 后发表回答