Search code examples
zend-frameworkzend-formzend-form-elementzend-validate

Zend Form MutliCheckbox Validate Number of Checked Items


I have a Zend Form with a MutliCheckbox element.

I would like to validate the number of checked items, i.e. verify that exactly 3 items are checked.

Can I do it with any current validates or do I have to write my own?

Thanks.


Solution

  • You will have to write your own, but that's quite simple. There is a second optional argument on the isValid() method that gives you access to all the form values, and enables this way to validate against multiple inputs.

    class MyValidator extends Zend_Validate_Abstract {
        public function isValid($value, $formData = null){
            //you can access to all the form values in the $formData, and check/count
            //the values of your multicheckbox
            //this is the super-quick way, but you could also add error messages
            return $isValid;
        }
    }
    

    and then add it to your element

    $myElement->addValidator( new MyValidator());