代码之家  ›  专栏  ›  技术社区  ›  Andy

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

  •  0
  • Andy  · 技术社区  · 7 年前

    alphanumeric with spaces CAKEPHP3.5.13中的验证。

    // 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或空格以外的字符,就会收到一条验证错误消息。

    然而…阅读 Using Custom Validation Rules ->add() 调用使用3个参数。

    我已经调查了来源( vendor/cakephp/cakephp/src/Validation/Validator.php

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

    如果我为第二个参数传递了一个数组,那么我的规则如何工作呢 $name

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

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

    无法在“默认”提供程序中调用“搜索名称”字段的方法

    1 回复  |  直到 7 年前
        1
  •  0
  •   Andy    7 年前

    对此,@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's的评论 source code 关于如何 add() 方法工作:

    将新规则添加到字段的规则集中。 则字段的规则列表将替换为第二个参数 第三个论点将被忽略

    在CakePHP 3.5.13中测试了这两种方法并给出了相同的结果

    推荐文章