如何验证ZF2中的复选框

Ale*_*lex 5 zend-framework zend-framework2

我已经阅读了Zend Framework缺少默认复选框验证的众多变通方法.

我最近开始使用ZF2,文档有点缺乏.

有人可以请证明我如何验证复选框以确保它被勾选,使用Zend表单和验证机制?我正在使用我的Forms的数组配置(使用ZF网站上的示例应用程序中的默认设置).

web*_*der 20

试试这个

表格元素:

$this->add(array(
            'type' => 'Zend\Form\Element\Checkbox',
            'name' => 'agreeterms',
            'options' => array(
                'label' => 'I agree to all terms and conditions',
                'use_hidden_element' => true,
                'checked_value' => 1,
                'unchecked_value' => 'no'
            ),
        ));
Run Code Online (Sandbox Code Playgroud)

在过滤器中,添加数字验证

use Zend\Validator\Digits; // at top

$inputFilter->add($factory->createInput(array(
                        'name' => 'agreeterms',
                        'validators' => array(
                            array(
                                'name' => 'Digits',
                                'break_chain_on_failure' => true,
                                'options' => array(
                                    'messages' => array(
                                        Digits::NOT_DIGITS => 'You must agree to the terms of use.',
                                    ),
                                ),
                            ),
                        ),
                    )));
Run Code Online (Sandbox Code Playgroud)

  • 一个很好的,优雅的解决方案,因为ZF2不断地和有意地使常见的日常任务尽可能困难和繁琐. (3认同)

Jef*_* S. 9

您也可以从选项中删除隐藏的表单字段(我从纯粹的HTML角度看起来有点奇怪),而不是将其值设置为"no",如下所示:

$this->add(array(
        'type' => 'Zend\Form\Element\Checkbox',
        'name' => 'agreeterms',
        'options' => array(
            'label' => 'I agree to all terms and conditions',
            'use_hidden_element' => false
        ),
    ));
Run Code Online (Sandbox Code Playgroud)