ZF2-571: Validation fails on multi_checkbox form type when nothing is checked.


If I create a form element of type MultiCheckbox, form submission will fail with a validation error when none of the checkboxes are selected, with a "Value is required and can't be empty" message.


// Build a name element.
$name = new Element('name');
$name->setLabel('Your name');
    'type'  => 'text'
// Build a submit button element.
$send = new Element('send');
    'type'  => 'submit',
    'value' => 'Send'
// Build a checkbox element.
$check = new Checkbox('check');
$check->setLabel('Checkbox example');
// Build a multi-checkbox element.
$multicheck = new MultiCheckbox('multicheck');
$multicheck->setLabel('Multi checkbox example');
    'value_options' => array(
        'One'   =>  'one',
        'Two'   =>  'two',

// Assemble the form.
$form = new Form('contact');

// Get the request if any.
$request = $this->getRequest();
$data = $request->getPost();

// Validate the form
if ($form->isValid()) {
    $validatedData = $form->getData();
    $success  = 'Form submit was successful';
} else {
    $success  = 'Form submit failed';
    $messages = $form->getMessages();

Validation will always fail in this case on the multicheck element.


The function {{getInputSpecification}} in Zend/Form/Element/Checkbox.php is the culprit as it sets "required" to true. Although "required" is not problematic for Checkbox elements it is a problem for multicheck elements because of the way the input data is returned to the form.

I suggest either:

  • Change {{getInputSpecification}} in Checkbox.php to set 'required' to be false, because checkboxes will have a checkedvalue and an uncheckedvalue and so this test is never hit for checkboxes.
  • Override {{getInputSpecification}} in MultiCheckbox.php to set 'required' to be false.


The attached files add to / replace those in the Zend Framework Skeleton Application to illustrate the issue.




Code tags added.

Added the simplest fix for this at https://github.com/zendframework/zf2/pull/2395

This issue has been closed on Jira and moved to GitHub for issue tracking. To continue following the resolution of this issues, please visit: https://github.com/zendframework/zf2/issues/2596