Cakephp验证功能不起作用

时间:2013-05-16 11:12:17

标签: php cakephp

这是我的模型 - >

<?php 
class Post extends AppModel {
 public $validate = array(
        'title' => array(

                'rule'     => 'alphaNumeric',
                'required' => true,
                'message'  => 'Alphabets and numbers only'
        ),
        'body' => array(
            'rule' => 'notEmpty'
        )
    );


}


?>

controller - &gt;

public function add() {
        if ($this->request->is('post')) {
            $this->Post->create();
            if ($this->Post->save($this->request->data)) {
                $this->Session->setFlash('Your post has been saved.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your post.');
            }
        }
    }

和查看 - &gt;

<h1>Add Post</h1>
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->end('Save Post');
?>

我怎样才能让它发挥作用。 我跟着他们在cakephp.org上提供的cakephp书,跟那里提到的完全相同,然后也无法做到正确

2 个答案:

答案 0 :(得分:0)

尝试使用更详细的数组声明:

class Post extends AppModel {
    public $validate = array(
        'title' => array(
            'alphaNumeric' => array(
                'rule'     => 'alphaNumeric',
                'required' => true,
                'message'  => 'Alphabets and numbers only'
            ),
        ),
        ...

等(注意更深层次的数组结构)记录(http://book.cakephp.org/2.0/en/models/data-validation.html)。

答案 1 :(得分:0)

在创建记录之前,只需从控制器设置和验证

public function add() 
{
            if ($this->request->is('post')) 
            {
                $this->Post->create();
                $this->Post->set($this->request->data['Post']); // Add this Line
                if ($this->Post->validates()) // Add this Line
                {
                  if ($this->Post->save($this->request->data)) 
                 {
                    $this->Session->setFlash('Your post has been saved.');
                    $this->redirect(array('action' => 'index'));
                 } 
                 else 
                 {
                    $this->Session->setFlash('Unable to add your post.');
                 }
                }
                else 
                 {
                    $this->Session->setFlash('Unable to add your post.');
                 }

            }
  }