On this page
Validators
NotEmpty Validator
This validator allows you to validate if a given value is not empty. This is often useful when working with form elements or other user input, where you can use it to ensure required elements have values associated with them.
Supported Options
The following options are supported for Laminas\Validator\NotEmpty
:
type
: Sets the type of validation which will be processed; for details, see the section on specifying empty behavior.
Default Behaviour
By default, this validator works differently than you would expect when you've
worked with PHP's empty()
operator. In particular, this validator will
evaluate both the integer 0
and string '0'
as empty.
$valid = new Laminas\Validator\NotEmpty();
$value = '';
$result = $valid->isValid($value);
// returns false
Specifying Empty Behavior
Some projects have differing opinions of what is considered an "empty" value: a
string with only whitespace might be considered empty, or 0
may be
considered non-empty (particularly for boolean sequences). To accommodate
differing needs, Laminas\Validator\NotEmpty
allows you to configure which types
should be validated as empty and which not.
The following types can be handled:
boolean
: Returnsfalse
when the boolean value isfalse
.integer
: Returnsfalse
when an integer0
value is given. By default, this validation is not activate and returnstrue
for any integer values.float
: Returnsfalse
when a float0.0
value is given. By default, this validation is not activate and returnstrue
on any float values.string
: Returnsfalse
when an empty string''
is given.zero
: Returnsfalse
when the single character zero ('0'
) is given.empty_array
: Returnsfalse
when an emptyarray
is given.null
: Returnsfalse
when anull
value is given.php
: Returnsfalse
on wherever PHP'sempty()
would returntrue
.space
: Returnsfalse
when an string is given which contains only whitespace.object
: Returnstrue
.false
will be returned whenobject
is not allowed but an object is given.object_string
: Returnsfalse
when an object is given and its__toString()
method returns an empty string.object_count
: Returnsfalse
when an object is given, it implementsCountable
, and its count is 0.all
: Returnsfalse
on all above types.
All other given values will return true
per default.
There are several ways to select which of the above types are validated. You can give one or multiple types and add them, you can provide an array, you can use constants, or you can provide a textual string. See the following examples:
use Laminas\Validator\NotEmpty;
// Returns false on 0
$validator = new NotEmpty(['type' => NotEmpty::INTEGER]);
// Returns false on 0 or '0'
$validator = new NotEmpty(['type' => NotEmpty::INTEGER | NotEmpty::ZERO]);
// Returns false on 0 or '0'
$validator = new NotEmpty(['type' => [ NotEmpty::INTEGER, NotEmpty::ZERO ]]);
// Returns false on 0 or '0'
$validator = new NotEmpty(['type' => ['integer', 'zero']]);