Question

In ZF2 I wrote a custom validator which checks if one of three form elements (element-A, elment-B, elment-C) is given. The custom validator is working fine. A am attching the validator to the form field "element-A".

The issue is: I have to set "setRequired" to "true" for "element-A", otherwise my custom validator is not triggerd. This forces the user to provide a vlaue for the form element the validator is attached to.

How can I trigger my custom validator without this former described behaviour?

Was it helpful?

Solution

The Zend\InputFilter\Input class has another parameter continue_if_empty which when used in combination with required and allow_empty will do what you need.

You can either set the param directly on the input filter element using the setContinueIfEmpty() method

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

Or, you can do the same by setting values in your input filter specification

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

Basically the above says this value must be present and may be empty, but if it is, validate it anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top