Custom validation rule in model

Hi,

i read this documentation https://book.cakephp.org/3.0/en/core-libraries/validation.html but i did not get it…

my validation function:

$validator
        ->boolean('a')
        ->requirePresence('a', 'create')
        ->notEmpty('a');

    $validator
        ->boolean('b')
        ->requirePresence('b', 'create')
        ->notEmpty('b');

    $validator
        ->scalar('c')
        ->maxLength('c', 255)
        ->allowEmpty('c');

    return $validator;

Possibilities:
a = 1 and b = 0
a = 0 and b = 1
a = 0 and b = 0 and c = not empty

Can some one help me?

Thanks!!!

Validation is for individual fileds. If you need logic involved more fileds than use application rules.

https://book.cakephp.org/3.0/en/orm/validation.html#application-rules

could you give a example to me?

I try to check in validation this:

if ($this->request->getData(‘a’)== 1 and $this->request->getData(‘b’)== 1){
return false
}

would be nice :wink:

You would need something like this

$rules->add(function ($entity, $options) {
    return ($entity->a == 1) && ($entity->b == 1);
}, 'aAndBAreOne');

Or if the check is more complicated than use an entity method

https://book.cakephp.org/3.0/en/orm/validation.html#using-entity-methods-as-rules

1 Like

You can use validation rules on multiple fields. In fact there is a core one that does that equalToField().

Validation is for verifying that data posted/injected by a user is correct (i.e. checking that entities have valid and expected data), while application rules are for testing application state before something is persisted into the database.

What @ole is describing sounds like validation to me :slight_smile:

You can easily do

$validator->add('a', 'correctValues', [
    'rule' => function ($data, $provider) {
        $a = $data;
        $b = $provider['data']['b'];
        $c = $provider['data']['c'];

        return !($a == 1 && $b == 1);
    }
]);
1 Like

Thanks! I’ll try it at weekend :wink: !