Question

What I want to do:

Adding custom ErrorMessages to my Zend_Form_Element_Text when certain validations fail. But here is my problem: Whatever I tried there where only all custom messages displayed or the default. Even the first StringLength validation displays only both cases.

Short example what I do:

$usernameElement = new Zend_Form_Element_Text('username', array('label' => 'Username'));
$usernameElement->setRequired(true);
$usernameElement->addValidator(
            new Zend_Validate_StringLength(array('min' => 3, 'max' => 32),true)
        );
$usernameElement->addErrorMessages(array(
            Zend_Validate_StringLength::TOO_SHORT => 'Username is too short',
            Zend_Validate_StringLength::TOO_LONG => 'Username is too long'));

I wasted a painfull amount of time on this and know it must be a really stupid mistake :(

Was it helpful?

Solution

You need to add the custom messages to the validator, not the element.

Something like:

$validator = new Zend_Validate_StringLength(array(
    'min' => 3, 
    'max' => 32,
    'messages' => array(
        Zend_Validate_StringLength::TOO_SHORT => 'Username is too short',
        Zend_Validate_StringLength::TOO_LONG => 'Username is too long',
    ),
));
$element->addValidator($validator, true);

There are aggregated short forms for this that can be used during element creation, adding an element to a form, etc. But the upshot is that typically, you override the validator messages on the validator, not on the element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top