Today, I have come across a bug in my Zend Framework application. This is the case:
I have a form with an element that has a regex validator on it. When testing the form, I found out that I can not provide the value 0 for the element. Zend gives me an error, telling me that I have not filled in the element.
The element:
$element = $this->createElement( "text", "amount", array( "label" => "Amount", "required" => true ) );
$element->addValidator( 'regex', false, array( '/^[-]?([0-9]+)(([,.][0-9]+)+)?$/' ) );
Can anyone tell me what the reason might be that Zend tells me I have not filled in the element when the submitted value is 0?
Thx
It's very simple, when you set "required" as true
, Zend_Form_Element automatically adds a notEmpty() validator at the top of the validators stack.
Therefore, any null, 0, "", etc. values are considered false
, and this validator set an error to your form.
See the manual for more information:
Default behaviour for Zend_Validate_NotEmpty
By default, this validator works differently than you would expect when you've worked with PHP's empty() function. In particular, this validator will evaluate both the integer 0 and string '0' as empty.
$valid = new Zend_Validate_NotEmpty();
$value = '';
$result = $valid->isValid($value);
// returns false