zend-framework2zend-formzend-validate

Zend Framework 2 MultiCheckbox and validatiors


Is there a way to validate an instance of Zend\Form\Element\MultiCheckbox using the Zend validators such as Zend\Validator\Digits?

I'm finding the existing Zend validators do not account for the fact that the selected value(s) is an array.

I found a reference here (http://zf2.readthedocs.io/en/release-2.2.7/modules/zend.form.element.multicheckbox.html) that the FormMultiCheckbox helper (https://framework.zend.com/manual/2.4/en/modules/zend.form.view.helper.form-multicheckbox.html) can be used to add an InArray validator to the element, but I'm not sure how that helps other types of validators. My usages show that it doesn't.

I realize I can extend the Zend Validators to account for the array, but I feel there has to be a way to do this which works with the rest of ZF2 out-of-the-box. If there isn't a way then I'll extend the validators, but I much rather use the out-of-the-box validators whenever possible.

Using:
zendframework/zend-form: 2.10.2
zendframework/zend-validator: 2.10.1


Solution

  • The Multicheckbox form element will only return the values that you define yourself, so there's no need to validate the values as long as you configure it correctly. The ZF3 Documentation gives the following example:

    use Zend\Form\Element;
    use Zend\Form\Form;
    
    $multiCheckbox = new Element\MultiCheckbox('multi-checkbox');
    $multiCheckbox->setLabel('What do you like ?');
    $multiCheckbox->setValueOptions([
            '0' => 'Apple',
            '1' => 'Orange',
            '2' => 'Lemon'
    ]);
    
    $form = new Form('my-form');
    $form->add($multiCheckbox);
    

    This element will always return an array of strings ('0', '1', and/or '2'). The element can also be written like this:

    use Zend\Form\Element;
    use Zend\Form\Form;
    
    $multiCheckbox = new Element\MultiCheckbox('multi-checkbox');
    $multiCheckbox->setLabel('What do you like ?');
    $multiCheckbox->setValueOptions([
            0 => 'Apple',
            1 => 'Orange',
            2 => 'Lemon'
    ]);
    
    $form = new Form('my-form');
    $form->add($multiCheckbox);
    

    This element will always return an array of integers (0, 1, and/or 2), and you don't need to validate to confirm that the selected values are integers.

    UPDATE

    For added security (in case there's a threat that users might try to change the values you coded in your multicheckbox code), the InArray validator can be used to indirectly validate that the inputs are digits by confirming that they are members of an array of the whitelist digits-only values that are the same that you included in your multicheckbox digit values.