如何显示cakephp 2.5.3模型验证消息。默认情况下它显示html 5验证消息

时间:2015-02-20 11:27:40

标签: html5 cakephp

如何显示CakePHP模型中定义的验证消息。当我提交表单时,CakePHP模型验证工作。但是不显示输入字段的验证消息。它显示了HTML 5验证消息。我想显示CakePHP模型验证消息。我正在使用CakePHP 2.5.3

以下是我的代码块:

控制器:

$this->User->set($this->request->data);
    if ($this->User->validates()) {
        if ($this->User->save($this->request->data)) {
            $Email->send();
            $this->Session->setFlash(__('The user has been created'));
            if ($this->Auth->login()) {

                $this->Session->setFlash(__('Welcome, ' . $this->Auth->user('username')));
                $this->redirect($this->Auth->redirectUrl());
            }
        } else {
            $this->Session->setFlash(__('The user could not be created. Please, try again.'));
        }
    }

型号:

public $validate = array(
    'username' => array(
        'nonEmpty' => array(
            'rule' => array('notEmpty'),
            'message' => 'A username is required',
            'allowEmpty' => false
        ),
        'unique' => array(
            'rule' => array('isUniqueUsername'),
            'message' => 'This username is already in use'
        ),
        'alphaNumericDashUnderscore' => array(
            'rule' => array('alphaNumericDashUnderscore'),
            'message' => 'Username can only be letters, numbers and underscores'
        ),
    )

查看:

<div id="divfirstname" class="input text required">
                    <label for="UserFirstname">First Name <span style="color:#FF0000">*</span></label>
                     <?php echo $this->Form->text('firstname');?>
                </div>

                <div id="divlastname"  class="input text required">
                    <label for="UserLastname">Last Name <span style="color:#FF0000">*</span></label>
                    <?php echo $this->Form->text('lastname');?>
                </div>
                <div class="input text required">
                    <label for="UserUsername">Username <span style="color:#FF0000">*</span></label>
                    <?php echo $this->Form->text('username');?>
                </div>

2 个答案:

答案 0 :(得分:0)

您不需要围绕保存呼叫包装验证块。

所以这就足够了:

    if ($this->User->save($this->request->data)) {
        $Email->send();
        $this->Session->setFlash(__('The user has been created'));
        if ($this->Auth->login()) {

            $this->Session->setFlash(__('Welcome, ' . $this->Auth->user('username')));
            $this->redirect($this->Auth->redirectUrl());
        }
    } else {
        $this->Session->setFlash(__('The user could not be created. Please, try again.'));
    }

CakePHP在调用Model->save()时自动处理验证,并在输入字段下显示错误。因此,如果$this->save因验证错误而失败,那么cakephp会在右侧输入字段下添加<div class="error-message">Message Text from your model validation array</div>

答案 1 :(得分:0)

您有2个选项:

  1. 要么不使用在客户端验证的cakePHP中的验证规则。

  2. 在DOM准备就绪时,请致电$("#formId").removeAttr('novalidate');

    $(document).ready(function(){ $("#formId").removeAttr('novalidate'); });