How can I pass an empty value through Zend framework 2 ValidatorChain to my custom validator?
It was possible on ZF1 by allowEmpty(false)
On ZF2 with empty element value :
If
allowEmpty = false
, NotEmptyValidator is added to the top of ValidatorChain withbreakOnFailure = true
,@see Zend/InputFilter/Input#injectNotEmptyValidator
.If
allowEmpty = true
, Element is considered as Valid,@see Zend/InputFilter/BaseInputFilter#isValid
if ($input->allowEmpty()) { $this->validInputs[$name] = $input; continue; }
Following works for ZF2 version 2.1.1:
The problem (if I got it correctly) is that in following example, for empty values of
'fieldName'
, no validation is triggered. This can be quite annoying, though inThis is quite annoying when you have particular cases, like checking an URL assigned to a page in your CMS and avoiding collisions (empty URL is still an URL!).
There's a way of handling this for empty strings, which is to basically attach the
NotEmpty
validator on your own, and avoiding calls tosetRequired
andsetAllowEmpty
. This will basically tellZend\InputFilter\Input#injectNotEmptyValidator
not to utomatically attach aNotEmpty
validator on its own:If you also want to check against
null
, you will need to extendZend\InputFilter\Input
as following:I see often the people making the mistake using
allowEmpty
in the inputFilter config arrays. The string should be written with underscore separation not with camel case. Soallow_empty
will work:meaning a field with key 'fieldName' must be present in the data, but its value is allowed to be empty.
If you like to use a separate form validate class or a array notation for validate, you can do as follows:
You can pass an array with
required => false
andallowEmpty => true
to input filter factory (as I remember you can pass it directly to input filter too - not so sure).This triggered validation of my
Callback
validator when the value was an empty string:The
allow_empty
initially invalidates the empty string and thecontinue_if_empty
allows it to then be evaluated by the validators that follow.continue_if_empty
solved my problem. Thanks to @dson-horácio-junior. This is what I used: