3
votes

Here I am again with an easy question.

Is there an existing zend validator to set a maximum to the boxes an user can select. I want them to select no more than 3 boxes.

I've searched the web and the only thing I've found was to set an error in the isValid function in the form element. But then I've got the problem the error is shown for each selected box. (so 4 or more times) Or maybe anyone knows how to deal with this problem? If I'd be able to display this error only once, my problem will be solved as well.

Thank you for helping.

2
Maybe group them, add a validator for the group you quickly write on your own. Display errors with the group then instead of each element.hakre

2 Answers

4
votes

You can use my validator, it checks against number of values. I used exactly for the same purposes - to validate max and min number of selected values in multiselect:

<?php
class App_Validate_ValuesNumber extends Zend_Validate_Abstract
{
    const TOO_LESS = 'tooLess';
    const TOO_MUCH = 'tooMuch';

    protected $_type = null;
    protected $_val = null;

    /**
     * @var array
     */
    protected $_messageTemplates = array(
        self::TOO_LESS => "At least %num% values required",
        self::TOO_MUCH => "Not more then %num%  required",
    );

    /**
     * @var array
     */
    protected $_messageVariables = array(
        'num' => '_val'
    );
    /**
     * Constructor for the integer validator
     *
     * @param string $type Comparison type, that should be used
     *                     TOO_LESS means that value should be greater then items number
     *                     TOO_MUCH means opposite
     * @param int    $val  Value to compare items number with
     */
    public function __construct($type, $val)
    {
        $this->_type = $type;
        $this->_val = $val;
    }

    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $value is a valid integer
     *
     * @param  string|integer $value
     * @return boolean
     */
    public function isValid($value)
    {
        // Value shoul dbe greated
        if ($this->_type == self::TOO_LESS) {
            if (count($value) < $this->_val) {
                $this->_error(self::TOO_LESS);
                return false;
            }
        }

        // Value should be less
        if ($this->_type == self::TOO_MUCH) {
            if (count($value) > $this->_val) {
                $this->_error(self::TOO_MUCH);
                return false;
            }
        }
        return true;
    }
}
1
votes

I just fought this today. It is a zend bug. http://framework.zend.com/issues/browse/ZF-11667. There is a diff for a fix in that issue, but it won't be in until 1.12 is out. I didn't want to wait so I patched my Zend_Form_Element. The fix works great. Before the fix my error messages on MultiChecks was repeated once for every box that was checked.