我的项目中有一名用户经理。当我添加用户时,必须调用所有验证,但根据我的要求,当我发送电子邮件时,用户登录密码然后我想要 isunique 验证电子邮件地址不被调用。
UserController.php
public function login() {
$this->layout = 'login';
if ($this->request->is('post')) {
/** these conditions are used to call validations forcefully **/
if (!empty($this->request->data)) {
$this->User->set($this->request->data);
if($this->User->validates()) {
}
} else {
$errors = $this->User->invalidFields();
}
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
} else {
//$errors = "Invalid email or password, try again";
$this->Session->setFlash(__('Invalid email or password, try again'));
}
}
}
user.php的
public $validate = array(
'email' => array(
'required' => array(
'rule' => 'notEmpty',
'message' => 'A email is required.'
),
'email' => array(
'rule' => array('email', true),
'message' => 'Please fill a valid email address.'
),
'isUnique' => array(
'rule' => array('isUnique'),
'message' => 'This email id already exist.'
)
),
'password' => array(
'rule' => 'notEmpty',
'message' => 'Please enter password.'
)
);
但是当我登录时显示"此电子邮件ID已经存在。"正确的电子邮件地址的消息,但如果数据库中存在电子邮件ID,我想跳过此验证。
答案 0 :(得分:1)
您可以使用beforeValidate()
(manual)回调,每次在验证之前触发回调,并且会在登录方式中设置某种标记。
所以在你的模型中添加标志字段:
protected $skipEmailUniqueValidation = false;
然后为它添加一些setter:
public function setSkipEmailUniqueValidation($value = true) {
$this->skipEmailUniqueValidation = $value;
}
并添加beforeValide()
方法:
public beforeValidate(array $options = array()) {
if ($this->skipEmailUniqueValidation) {
unset($this->validate['email']['isUnique']);
}
return parent::beforeValidate($options);
}
最后要做的是在您的操作中设置skipEmailUniqueValidation
:
public function login() {
$this->layout = 'login';
if ($this->request->is('post')) {
/** these conditions are used to call validations forcefully **/
if (!empty($this->request->data)) {
$this->User->set($this->request->data);
$this->User->setSkipEmailUniqueValidation(true); // here
if($this->User->validates()) {
}
} else {
$errors = $this->User->invalidFields();
}
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
} else {
//$errors = "Invalid email or password, try again";
$this->Session->setFlash(__('Invalid email or password, try again'));
}
}
}