这是我在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));
但这是有据可查的。
仅当您确实需要分两步执行此操作时,后者才有意义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句