cakephp3 自定义验证

cakephp3 custom validation

我有一个 duration 字段,有时可以为空,有时不能,具体取决于表单发送的其他数据。所以我正在尝试在 CakePHP3 中进行自定义验证。

在我的 table 我做到了

public function validationDefault(Validator $validator)
{
    $validator
    ->add('duration', 'durationOk', [
        'rule' => 'isDurationOk',
        'message' => 'duration is not OK',
        'provider' => 'table'
    ]);
    return $validator;
}

public function isDurationOk($value, $context)
{
    // do some logic
    return false; // Always return false, just for test
}

现在,当我设置持续时间字段的值时,出现 'duration is not OK' 错误(正如预期的那样)。但是当我让这个值为空时,我得到一个 'This field cannot be left empty' 错误。

所以我补充说:

->allowEmpty('duration');

但在这种情况下,当 duration 为空时,我根本不会收到错误消息。

我是做错了什么还是只是我不明白验证是如何工作的?

让我read the book为你:

Conditional Validation

When defining validation rules, you can use the on key to define when a validation rule should be applied. If left undefined, the rule will always be applied. Other valid values are create and update. Using one of these values will make the rule apply to only create or update operations.

Additionally, you can provide a callable function that will determine whether or not a particular rule should be applied:

'on' => function ($context) {
    // Do your "other data" checks here
    return !empty($context['data']['other_data']);
}

因此,只需在回调中根据您的 "other data" 定义条件,以便仅在条件为真时应用规则。

或者,您甚至可以在 table 的 beforeMarshal() 回调中验证原始表单数据之前对其进行操作,并根据需要更改表单数据或加载另一个验证器或修改验证器。