如何在 CakePHP 3 验证中逻辑比较值(数字)字段值

How to logically compare values (numbers) field values in CakePHP 3 validation

我正在尝试使用 comparison rule,但似乎遗漏了某些内容或未正确使用。基本上我需要的是验证以检查 small_size 的值是否小于或等于 big_size

但这不起作用,无论大小如何,我目前都会收到错误消息。

Table:

     ...
     $validator
        ->add('small_size', 'valid', ['rule' => 'numeric'])
        ->requirePresence('small_size', 'create')
        ->notEmpty('small_size')
        ->add('small_size', 'comparison', [
            'rule' => ['comparison', 'big_size', '<='],
            'message' => 'Small size cannot be more than the Big size.'
        ]);
    return $validator;
}

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['Entity_id'], 'Entity'));
    return $rules;
}

我们将不胜感激。

您不能使用内置 comparison rule to compare two fields, you need to use a custom rule:

$validator->add('small_size', 'comparison', [
    'rule' => function ($value, $context) {
        return intval($value) <= intval($context['data']['big_size']) ;
    },
    'message' => 'Small size cannot be bigger than Big size.'
]);

您可以使用 compareFields 方法比较两个字段 https://api.cakephp.org/3.6/class-Cake.Validation.Validation.html#_compareFields

喜欢:

->add('small_size', 'compareFields', [
        'rule' => ['compareFields', 'small_size','big_siz', '<='],
        'message' => 'Small size cannot be bigger than Big size.'
    ]);