【问题标题】:Zend Framework 2 - Form Validation - Validator which checks if one of three form fields is givenZend Framework 2 - Form Validation - 验证器,它检查是否给出了三个表单字段之一
【发布时间】:2014-06-21 20:16:48
【问题描述】:

在 ZF2 中,我编写了一个自定义验证器,它检查是否给出了三个表单元素(元素-A、elment-B、elment-C)之一。自定义验证器工作正常。 A 正在将验证器附加到表单字段“element-A”。

问题是:我必须将“element-A”的“setRequired”设置为“true”,否则我的自定义验证器不会被触发。这会强制用户为验证器附加到的表单元素提供一个值。

如果没有前面描述的行为,我如何触发我的自定义验证器?

【问题讨论】:

    标签: php forms validation frameworks zend-framework2


    【解决方案1】:

    Zend\InputFilter\Input 类有另一个参数continue_if_empty,当它与requiredallow_empty 结合使用时,可以满足您的需要。

    您可以使用setContinueIfEmpty() 方法直接在输入过滤器元素上设置参数

    $elementA->setRequired(true);
    $elementA->setAllowEmpty(true);
    $elementA->setContinueIfEmpty(true);
    

    或者,您可以通过在输入过滤器规范中设置值来做同样的事情

        $inputFilter->add([
            'name' => 'elementA',
            'required' => true,
            'allow_empty' => true,
            'continue_if_empty' => true,
            'filters' => [
                //..
            ],
            'validators' => [
                //..
            ],
        ]);   
    

    基本上上面说这个值必须存在并且可能为空,但如果是,无论如何都要验证它。

    【讨论】:

    • 我不知道“continue_if_empty”标志。它现在正在工作。谢谢。因为在我的例子中“ElementA”是一个 MultiCheckBox,所以在创建元素时我还必须使用标志“disable_inarray_validator”。否则,“NotInArray”验证器会触发在我的“value_options”中找不到空值的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多