如何显示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>
您不需要将验证块封装在保存调用中。
所以这就足够了:
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
由于验证错误而失败,cakepp会在右侧输入字段下添加<div class="error-message">Message Text from your model validation array</div>
。
您只剩下两个选项:
-
要么不要在cakeHP中使用验证规则,后者在客户端进行验证。
-
在DOM就绪时,像一样调用
$("#formId").removeAttr('novalidate');
$(document).ready(function(){ $("#formId").removeAttr('novalidate'); });