我是 cakePHP 的新手,我按照一些教程制作了一个简单的表单。在这个 html 表单上,我使用了验证。现在的问题是验证工作正常,但消息没有显示我想要它显示的内容。我尝试了下面的代码。
型号
public $validate = array(
'title' => array(
'title_required' => array(
'rule' => 'notEmpty',
'message' => 'This is required field'
),
'title_unique' => array(
'rule' => 'isUnique',
'message' => 'This should be unique title'
)
)
);
Controller
public function add() {
if ($this->request->data) {
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash('Post has been added successfully');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Error occured, Please try agan later!');
}
}
}
查看
<h2>Add New Post</h2>
<?php
echo $this->Form->create('Post', array('action'=>'add'));
echo $this->Form->input('title');
echo $this->Form->input('body');
echo $this->Form->end('Create Post');
?>
我看到的验证错误不是我在 Controller 中提到的消息。
最佳答案
这是内置的浏览器验证。
自 2.3 起,HTML5 required 属性也将根据验证规则添加到输入中。
你的 title
有 notEmpty
规则,所以 Cake 正在输出
<input type="text" required="required" ..
并且您的浏览器正在触发该消息。
编辑:要覆盖此行为,您可以执行以下操作:
$this->Form->input('title', array('required'=>false));
或
$this->Form->submit('Submit', array('formnovalidate' => true));
当您提交表单时,您的模型验证将触发。
关于php - CakePHP : Validation message not displaying,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14723685/