cakephp登录表单验证空白用户名和密码

时间:2012-12-10 20:38:57

标签: cakephp cakephp-2.1

我已经检查了cakephp验证很长时间以验证我的登录表单。我的问题是当我输入用户名和密码为空白时验证没有显示。

UserController.php中的登录功能包含

 if ($this->request->is('post')) {
            $this->user->set($this->request->data);
            $errors = $this->user->invalidFields(); 

            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash($this->Auth->authError, 'default', array(), 'auth');
                $this->redirect($this->Auth->loginAction);
            }
        } else {

            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirect());
            }
        }

我的User.php模型包含验证器

 public $validate = array(
        'username' => array(
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'The username has already been taken.',
            ),

            'notEmpty' => array(
                'rule' => 'notEmpty',
                'message' => 'This field cannot be left blank.',
            ),
        ),
        'email' => array(
            'email' => array(
                'rule' => 'email',
                'message' => 'Please provide a valid email address.',
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'Email address already in use.',
            ),
        ),
        'password' => array(
            'rule' => array('minLength', 6),
            'message' => 'Passwords must be at least 6 characters long.',
        ),
        'current_password' => array(
            'rule' => '_identical',
            ),
        'name' => array(
            'rule' => 'notEmpty',
            'message' => 'This field cannot be left blank.',
        ),
    );

实际上我的登录表单只包含usgername和密码。但我已为userregistration表单设置了此验证。验证在注册表单中正常工作,但在登录时验证无效。是的,我知道在这个网站上发布了很多关于同一问题的问题,但没有解决我的问题,我已经尝试了所有的stackoverflow问题。请帮忙

1 个答案:

答案 0 :(得分:0)

验证仅在保存时或使用以下方法直接调用验证方法时发生:

$this->Model->validates();

您没有收到验证错误,因为您实际上并未验证数据。要获得验证错误,您需要执行以下操作:

if ($this->request->is('post')) {
        $this->User->set($this->request->data);
        if ($this->User->validates()) {
             echo "This is valid!";
        } else {
             echo "This is invalid";
             $errors = $this->User->validationErrors;
        }
}