cakephp 2.4.x中没有显示验证消息

时间:2014-05-16 02:05:31

标签: php cakephp

以下是User.php中的验证规则

public $validate = array(
    'username' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'User name is required'
        ),
        'alphaNumeric'=>array(
            'rule' => 'alphaNumeric',
            'required' => true,
            'message' => 'Alphabets and numbers only'
        )
    ))

这是我的查看页面代码

<?php
      echo $this->Form->create('User');
      echo $this->Form->input('username', array('label' => 'Username'));
      echo $this->Form->input('email', array('label' => 'Email'));
      echo $this->Form->input('password', array('label' => 'Password'));
      echo $this->Form->submit('Sign Up');
      echo $this->Form->end();
?>

这是我的控制器代码

public function register() {
$this->layout = 'starter';
//debug($this->validationErrors);
if ($this->request->is('post')) {
    if ($this->User->validates()) {
        $this->User->save($this->request->data);
        $this->Session->setFlash(__('Please login your account'));
        $this->redirect('/users/login');
      } else {
        $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
      }
 }
}

但未显示验证消息。我的代码出了什么问题?...

3 个答案:

答案 0 :(得分:1)

你的代码错了。

if ($this->request->is('post')) {
    if ($this->User->validates()) {
        $this->User->save($this->request->data);

这不是它的工作原理,因为在验证之前没有传递数据。

您需要首先传递数据,然后验证,然后选择保存(或一起保存和验证):

if ($this->request->is('post')) {
    if ($this->User->save($this->request->data)) {}

,注意不要重新启动两次验证:

if ($this->request->is('post')) {
    $this->User->set($this->request->data);
    if ($this->User->validates()) {
        $success = $this->User->save(null, array('validate' => false));

但是记录在案。

如果你真的需要分两步完成,那么后者才有意义。

答案 1 :(得分:0)

在你的评论中,你写过你已经改变了布局页面。你可能会错过

<?php echo $this->Session->flash(); ?>

此行。在view / layouts / yourlayout.ctp文件中添加此行。

答案 2 :(得分:0)

在视图页面代码中停用HTML5 required

<?php
  echo $this->Form->create('User');
  echo $this->Form->input('username', array('label' => 'Username','required'=>'false'));
  echo $this->Form->input('email', array('label' => 'Email','required'=>'false'));
  echo $this->Form->input('password', array('label' => 'Password','required'=>'false'));
  echo $this->Form->submit('Sign Up');
  echo $this->Form->end();
?>