CakePHP3.x自定义验证无效

时间:2014-08-21 13:52:10

标签: cakephp cakephp-3.0

在UsersTable类中,我试图在CakeBook之后实现自定义验证,但我收到一条错误,Object of class App\Model\Table\UsersTable could not be converted to string [CORE/src/Validation/ValidationRule.php, line 128]。以下是我在UsersTable.php中的代码。

class UsersTable extends Table{
    public function validationDefault(Validator $validator){
        $validator->add(
            "password",[
                 "notEmpty"=>[
                     "notEmpty"
                 ],
                 "custom"=>[
                     "rule"=>[$this,"customFunction"],
                     "message"=>"foo"
                 ]
             ]
        );
    }
    public function customFunction($value,$context){
        //some logic here
    }
}

查看核心CakePHP库中的ValidationRule.php,我注意到array_shift()(第185行)正在使用[$this,"customFunction"]的第一个元素,即$this和将其分配给$value。但实际上$value应为[$this,"customFunction"]。因此,为了使我的代码能够正常工作,我需要再添加一个嵌套到[$this,"customFunction"](现在它是[[$this,"customFunction"]])。我是误解了某些东西还是某种错误?

UPD:此问题现已修复。

2 个答案:

答案 0 :(得分:1)

我认为您已经正确地发现,问题似乎是CakePHP期望rule键值在

[string or callable, ...args]

格式化时,即它不会测试值本身是否已经可调用。

文档说非嵌套变体应该有效,所以你可能想把它报告为bug。

答案 1 :(得分:1)

在您的模型中使用它进行自定义验证

public function validationCustom($validator)
{
    return $validator
        ->notEmpty('username', 'A username is required');
}

当您要保存或更新

时,在控制器中使用验证方法名称除验证关键字
$user = $this->Articles->newEntity($this->request->data,
        ['validate' => 'custom']);