【问题标题】:CakePHP3.x custom validation not workingCakePHP3.x 自定义验证不起作用
【发布时间】:2014-08-21 13:52:10
【问题描述】:

在 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:此问题现已修复。

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

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

    [string or callable, ...args]
    

    在数组中的格式,即它不测试值本身是否已经是可调用的。

    文档说非嵌套变体应该可以工作,因此您可能希望将此报告为错误。

    【讨论】:

    • 如何将此报告为错误?在 github 上?非常感谢您多次回答我的问题:)
    • 好的。我会做。谢谢。
    【解决方案2】:

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

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

    当你想保存或更新时,在你的控制器中使用验证方法名称,除了验证关键字

    $user = $this->Articles->newEntity($this->request->data,
            ['validate' => 'custom']);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      相关资源
      最近更新 更多