zendframework / zend-inputfilter

InputFilter component from Zend Framework
BSD 3-Clause "New" or "Revised" License
64 stars 50 forks source link

Filter to boolean and non-required input #99

Closed fust closed 8 years ago

fust commented 8 years ago

I noticed some strange behaviour today:

$input= new \Zend\InputFilter\Input();
$input->setValue("0");
$input->getFilterChain()->attachByName('boolean');
$input->setRequired(false);

$input->isValid(); //return false

The input gets filtered to a boolean value (false) before being validated. Because both allowEmpty and continueIfEmpty are false by default the NotEmpty validator is attached to the validator chain. The value "false" gets passed to the NotEmpty validator which, correctly, marks it as "invalid".

This results in strange "This field is required...." messages after validation on non-required inputs, while boolean false is a perfectly valid, non-empty value for e.g. a checkbox element.

Maks3w commented 8 years ago

Its better set allowEmpty and continueIfEmpty as true and attach the NonEmpty validator if you need.

$input = new Input();
$input->setAllowEmpty(true);         // Disable BC Break logic related to treat `null` values as valid empty value instead *not set*.
$input->setContinueIfEmpty(true);    // Disable BC Break logic related to treat `null` values as valid empty value instead *not set*.
$input->getValidatorChain()->attach(
    new Zend\Validator\NotEmpty(),
    true                             // break chain on failure

);
fust commented 8 years ago

I agree it's best to disable the BC break logic in new code. I don't actually need the NotEmpty validator a lot so that's not the issue here. However, it's not desireable to modify dozens (or even hundreds in enterprise applications) of existing forms/filters after an update to the framework just because the input filter logic itself is broken. Especially when this can be fixed in a future release.

Maks3w commented 8 years ago

It can't be fixed.