Cakephp,验证消息未显示

时间:2015-02-26 19:42:13

标签: php cakephp

我无法在CakePHP控制器类中捕获并显示验证错误。 我有这个模特:

public $validate = array(
    'username' => array(
        'notEmpty' => array(
            'rule' => array('notEmpty'),
            'message' => 'Your custom message here',
            'allowEmpty' => false,
            'required' => true,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'alphaNumeric' => array(
            'rule' => array('alphaNumeric'),
            'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),
        'maxLength' => array(
            'rule' => array('maxLength', 50),
            'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
        ),

    ));

这就是我在将新元素保存到数组时尝试将验证消息捕获到控制器中的方法:

public function add() {

    if ($this->request->is('post')) {
        $this->Admin->set($this->request->data);
        //$this->Admin->create();
        if ($this->Admin->validates()) {
            // it validated logic
            if ($this->Admin->save($this->request->data)) {
                $this->Session->setFlash(__('The admin has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The admin could not be saved. Please, try again.'));
            }
        } else {
            // didn't validate logic
            $errors = $this->Admin->validationErrors;
            debug($errors);
        }
    }
}

但它不起作用。如果我传递一个空字段,则会在add.ctp页面中显示带有默认消息的警报。如果我插入副本,则不会显示任何消息。

1 个答案:

答案 0 :(得分:1)

您不需要

$this->Admin->set($this->request->data);
$this->Admin->validates(){}

因为如果您使用“保存”

$this->Admin->save($this->request->data)

已经验证了。那应该可以胜任。