CakePHP 3 - 验证 'add()' 方法使用 2 个参数,但方法签名表明应该有 3 个

CakePHP 3 - validation 'add()' method is working with 2 parameters but method signature suggests there should be 3

我正尝试在 CakePHP 3.5.13 中进行 alphanumeric with spaces 验证。

所以我将以下内容添加到我的 Table 类 之一:

// src/Model/Table/SavedSearchesTable.php

public function validationDefault(Validator $validator)
{
    $validator->add('search_name', [
        'alphanumeric' => [
            'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
            'message'  => 'Alphanumeric characters with spaces only'
            ]
        ]);

     return $validator;
 }

这正是我想要的 - 如果我输入的字符串包含 A-Z、0-9 或 space.

以外的字符,我会收到一条验证错误消息

但是...在文档中阅读有关 Using Custom Validation Rules 的所有 ->add() 调用都使用 3 个参数。

我查看了源代码 (vendor/cakephp/cakephp/src/Validation/Validator.php),方法如下所示:

public function add($field, $name, $rule = [])
{
    // ...
}

如果我为第二个参数传递了一个数组,我的规则如何工作,它被视为 $name

Edit :有人在评论中提到旧代码有 fallback。好吧,如果我尝试在模型中使用 3 个参数(而不是 2 个)(注意添加 'custom' 作为第二个参数):

$validator->add('search_name', 'custom', [
        'alphanumeric' => [
            'rule' => ['custom', '/^[a-z0-9\' ]*$/i'],
            'message'  => 'Alphanumeric characters with spaces only'
            ]
        ]);

它现在产生一个错误:

Unable to call method "" in "default" provider for field "search_name"

@ndm 在评论中提供了正确答案。

我正在写一个完整的例子以防其他人遇到这个问题。

可以或者写成:

$validator->add(
        'search_name', 
        'alphanumeric', 
        [
            'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
            'message'  => 'Alphanumeric characters with spaces only'
        ]
);

或:

$validator->add('search_name', 
    [ // second argument is an array. This was how it was in the original question.
        'alphanumeric' => 
             [
                 'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
                 'message'  => 'Alphanumeric characters with spaces only'
             ]
    ]
);

以下是 Cake 的 source code 中关于 add() 方法如何工作的评论:

Adds a new rule to a field's rule set. If second argument is an array then rules list for the field will be replaced with second argument and third argument will be ignored.

这两个都已经过测试,在 CakePHP 3.5.13 中给出了相同的结果