Originally posted in my old blog at My Opera
Zend_Filter_Input, while a very useful component of the Zend Framwork, has some oddities that can cause a lot of headache if you can't figure it out right away.
- Missing fields show up as valid even if they have validators that won't let empty values through
- NULL values for existing fields
to name some.
Missing field problems
If you are validating some data which doesn't always contain a certain field, but to be valid, it requires it to contain the field, you may run into some problems.
For example, if you create a form with a checkbox and the checkbox must be checked for the form to be valid.
If you write a rule which specifies something like:
$validators = array( 'checkbox' => 'NotEmpty' );
the data will be valid if the checkbox was not checked. When a checkbox isn't checked, the data doesn't exist at all in the POST array.
By default, Zend_Filter_Input ignores missing fields which seems somewhat odd to me. If you define a validator for a field which will validate when the field is not empty, why is it valid when the field doesn't exist? A field which doesn't exist in the data is definitely empty.
To fix this, add a presence parameter to the validator array:
$validators = array( 'checkbox' => array( 'presence' => 'required', 'NotEmpty' ) );
Now the data will not validate if the checkbox field isn't present.
Null values
If you pass an array to Zend_Filter_Input and try using the methods in it to get the data, you end up getting null values. But why?
Zend_Filter_Input will ignore all data that doesn't have a filter or a validator rule specified. Thus, it will give null values for every such field. You will need to add allowEmpty rules for the fields which have no other rules:
$validators = array( 'somefield' => 'Alpha', 'somefield2' => array('allowEmpty' => true), 'somefield3' => array('allowEmpty' => true) );
Now you can use the methods in Zend_Filter_Input to get the rest of the fields.
Other issues
Catchable fatal error: Argument 1 passed to Zend_Validate::addValidator() must implement interface Zend_Validate_Interface, integer given, called in /library/Zend/Filter/Input.php on line 639 and defined in library/Zend/Validate.php on line 69
This error is caused if you try to create a validator with parameters in the wrong format.
At first, it might seem that this will work:
$validators = array( 'myfield' => array('StringLength',1,1) );
however, it does not work. You will have to use one more array:
$validators = array( 'myfield' => array(array('StringLength',1,1)) );
Outside these, the component works quite well. It would seem obvious that fields which have validators declared should exist in the data, and fields in the data should be passed to the Zend_Filter_Input class even if they don't have any filters or validators defined… but it seems that the designers of the class have thought otherwise. Who knows, maybe they will change the default behavior to a more predictable one in the future.