Custom validation rule in model


i read this documentation but i did not get it…

my validation function:

        ->requirePresence('a', 'create')

        ->requirePresence('b', 'create')

        ->maxLength('c', 255)

    return $validator;

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

Can some one help me?


Validation is for individual fileds. If you need logic involved more fileds than use 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

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: !