Search code examples
validationcakephpcakephp-3.x

Why does the `notEmpty` rule not apply when the field is missing in the data?


I'm try to create a validation for a new created entity but the entity object does not contain any errors here the code:

Model Class:

public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmptyString('id', null, 'create');

    $validator
        ->integer('status')
        ->notEmptyString('status');

and the controller:

$data = ['data' => "test"];

    $ticket = $this->Tickets->newEntity($data);

the result:

object(Cake\ORM\Entity) {

'data' => 'test',
'[new]' => true,
'[accessible]' => [
    '*' => true
],
'[dirty]' => [
    'data' => true
],
'[original]' => [],
'[virtual]' => [],
'[hasErrors]' => false,
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Tickets'

}

i think the default setting is the validationDefault is used and the error field must contain an error because "status" is not set. but the "erros" field is always empty and if i call the "save" function the entity save to the database.

how i can fix this ?


Solution

  • That's not how notEmpty rules work, they do not require a field to be present, they require the field to be not empty only in case it is present. When the field isn't present, the empty rule (or any other rule for that matter) simply will not apply, ie this would make your rule fail:

    [
        'status' => ''
    ]
    

    If you want to enforce the field being present, use the requirePresence rule, like:

    $validator
        ->requirePresence('status', 'create')
        ->notEmptyString('status')
        ->integer('status');
    

    The order doesn't really matter here, as the presence and empty checks are executed in a fixed order, that is first presence check, then empty check, and then all other rules, but IMHO it's easier to understand when the order of the calls reflects that.

    See also