下面是我在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.'));
}
}
}
但是没有显示验证消息。
你的代码是错误的。
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));
但这是有记录的。
后一种方法只有在需要分两步完成时才有意义。
在你的评论中你写了你已经改变了布局页面。你可能会错过
<?php echo $this->Session->flash(); ?>
这条线。在view/layouts/yourlayout中添加这一行。ctp文件。
在视图页面代码中禁用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();
?>