I don't know if this is too much for you.
$element = new Zend_Form_Element_Multiselect('CheckThis'); $options = array( 1 => 'Option One', 2 => 'Option Two', 3 => 'Option Three', 4 => 'Option Four', 5 => 'Option Five', 6 => 'Option Six', 7 => 'Option Seven', 8 => 'Option Eight', ); $element->addMultiOptions($options); $betweenOptions = array('min' => 2, 'max' => 4); $betweenValidator = new Zend_Validate_Between($betweenOptions); $betweenValidator->setMessage("The number of submitted values '%value%' is not between '%min%' and '%max%', inclusively",'notBetween'); if ( true === $this->getRequest()->isPost() ) { if ( true === $betweenValidator->isValid(count($_POST['CheckThis'])) ) { $form->isValid($_POST); } else { $messages = $betweenValidator->getMessages(); $element->addError($messages['notBetween']); $form->setDefaults($_POST); } }
UPDATE
Note to avoid duplicate error messages.
If you cannot call isValid on a form or element; as in my example, where I only add an error message and set the default values. The problem is that isValid($value) will call _getErrorMessages() , and this method checks for error messages for values.
If you cannot avoid calling isValid , I would extend the Multiselect element and override this _ getErrorMessages() method with my one logic. This method can be found in the Zend/Form/Element.php class to the end.
source share