CakePHP没有检查表单验证

时间:2013-02-09 19:26:05

标签: php validation cakephp view model

我正在撰写联系表单并希望添加一些简单的验证例程。此页面的操作如下所示:

public function contact() {
    $this->loadModel('Contact');

    $this->set('pageTitle', 'Contact me');
}

并且Contact模型是这样的:

<?php

class Contact extends AppModel {
public $useTable = false;

public $validate = array(
    'name' => array(
        'between' => array(
            'rule' => array('between', 1, 60),
            'message' => 'Between 1 and 60 characters in length'
        )
    ),
    'email' => array(
        'kosher' => array(
            'rule' => 'email',
            'message' => 'Please make sure your email is entered correctly'
        ),
    ),
    'message' => array(
        'between' => array(
            'rule' => array('between', 1, 65000),
            'message' => 'Between 1 and 65000 characters in length'
        )
    )
);

}

最后是我的观看页面:

<?php echo $this->Form->create('Contact'); ?>
<?php echo $this->Form->input('name'); ?>
<?php echo $this->Form->input('email'); ?>
<?php echo $this->Form->input('message', array('type' => 'textarea')); ?>
<?php echo $this->Form->end(array('label' => 'Send', 'class' => 'btn btn-primary')); ?>

但是,当我使用不正确的值提交表单时,不会调用验证例程,也不会显示错误消息。

如何让Cake验证表格?

2 个答案:

答案 0 :(得分:0)

在您的联系人操作中,您所做的只是加载联系人模型。您必须显式调用相关的模型方法来执行验证。请正确阅读manual以了解具体方法。

答案 1 :(得分:0)

在文档中查看如何从控制器中的表单插入/更新数据。你会看到这样的事情:

if ($this->request->is('post')) {
    if ($this->Contact->save($this->request->data)) {
        // handle the success.
    } else {
       $this->Session->setFlash(__('The Contact could not be saved. Please, try again.'));
    }
}