Saturday
2
January
2010

New Zend_Validate_NotEmpty implementation

First a happy new year to all reading my blog. :-)

I hope this year will become better than the last. Not that the last year was bad… it was really good. But things can always get better. ;-)

And now to business:

Today I added a completly new implementation for the “not empty” validator. Zend_Validate_NotEmpty worked in past only the “framework” way. It detected whitespaces as empty and excluded ‘0′. This collidates with how PHP’s empty() works.

The new implementation which is available with Zend Framework 1.10 allows you to customize this behaviour.
You are not only able to do validations conform to empty() but you are also able to customize which input to detect as empty and which not.

Let’s go into details:
Zend_Validate_NotEmpty allows to define a constant for each type which it has to accept.

$validator = new Zend_Validate_NotEmpty();
var_dump($validator->isValid('0'));

The above returns false.

Now let’s emulate PHP’s default behaviour:

$validator = new Zend_Validate_NotEmpty(Zend_Validate_NotEmpty::PHP);
var_dump($validator->isValid('0'));

As you will see, the above returns true.

So simply by defining the type you can change the behaviour of this validator.
The following types are accepted:
* BOOLEAN (true/false)
* INTEGER (0)
* FLOAT (0.0)
* STRING ('’)
* ZERO (’0′)
* EMPTY_ARRAY (array())
* NULL (null)
* PHP (emulates PHP’s empty() behaviour)
* SPACE (’ ‘)
* ALL (all above)

You can also give multiple types as array:

$validator = new Zend_Validate_NotEmpty(
    array(
        Zend_Validate_NotEmpty::INTEGER,
        Zend_Validate_NotEmpty::ZERO
    )
);

The above would only validate 0 and the string 0 as empty.
And for simplification you can also give a Zend_Config object.

This new behaviour fixes several problems and issues which have been experienced in past.
I hope you will find this new extension useful.

Have fun and a happy new year.

Greetings
Thomas Weidner
I18N Team Leader, Zend Framework

Zend Framework Advisory Board Member
Zend Certified Engineer for Zend Framework

Back to top
  1. Ernie

    Wednesday, May 23, 2012 - 13:00:04

    Great post, never heard about it, check my website http://ifun.hut4.ru/ if you wand something fun.
    Visiting http://ifun.hut4.ru/ is a great opportunity to have fun :)