dowjgrm6787 2014-05-16 02:05
浏览 18
已采纳

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

Here is my validation rule in 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'
        )
    ))

and this is my view page code

<?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();
?>

Here is my controller code

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.'));
      }
 }
}

but validation message is not showing. What is wrong in my code?...

  • 写回答

3条回答 默认 最新

  • douqi1928 2014-11-14 23:11
    关注

    Your code is wrong.

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

    this is not how it could ever work as the data is not passed prior to validation.

    You need to first pass the data, then validate, then optionally save (or save and validate together):

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

    or, careful not to retrigger validation twice:

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

    But that is documented.

    The latter only makes sense if you really need to do this in two steps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 MATLAB四叉树处理长方形tif文件
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了