Model-> validates()似乎不起作用

时间:2014-01-30 04:31:30

标签: cakephp

我目前正在使用cakephp 2.4.5并且遇到Model :: validates()的问题。由于某种原因,它不起作用......这是一个正在发生的事情的样本:

控制器:

$this->Transaction->create();
$this->Transaction->set($this->request->data);

if ($this->Transaction->validates()) {
    if (!$this->Transaction->save($this->request->data)) {
        //why is this happening, how is it possible????
        pr($this->Transaction->validationErrors);
    }   
} else {
    $this->Session->setFlash('validation failed');
}

查看:

<?php echo $this->Form->create('Transaction');?>
<?php echo $this->Form->input('Address.address'); ?>
<?php echo $this->Form->input('amount'); ?>
<?php echo $this->Form->input('User.password'); ?>
<?php echo $this->Form->end('Submit')); ?>

在视图中,显示的唯一错误消息是地址和金额,密码验证错误不会显示...

pr($this->Transaction->validationErrors);
Array
(
    [Address] => Array
        (
            [address] => Array
                (
                    [0] => The address you provided does not appear to be valid. Please try again.
                )

        )

    [User] => Array
        (
            [password] => Array
                (
                    [0] => Your password must be between 6 and 12 characters in length.
                )

        )

)

有什么想法吗?我错过了什么?

1 个答案:

答案 0 :(得分:0)

我不确定你的意思是“它不起作用”,但我注意到了一件事。当我手动调用验证时,我使用相等比较。此外,在验证之前,不要为事务创建新条目。我不确定这是否会导致错误,但无论如何,如果输入未通过验证,您不希望它创建条目。

if ($this->Transaction->validates() == true){
    $this->Transaction->create(); //this goes after the validation, not before
  

在视图中,显示的唯一错误消息是地址和金额,密码验证错误不会显示...

编辑验证似乎只从一个模型中进行选择。尝试单独验证模型

if($this->Transaction->validates() == true){
   $this->loadmodel('User'); //assuming you don't arleady have it loaded
   if($this->User->validates(array('fieldList' => array('password'))) == true) {