我有一个注册表单,用户在注册时会询问用户名,密码和电子邮件。对于用户名,我有一些规则,例如:
话虽如此,我似乎无法获取重复用户名的形式,我希望有人可以帮我解决这个问题!
这是我的User.php模型的验证:
public $validate = array(
'username' => array(
'nonEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required',
'allowEmpty' => false
),
'between' => array(
'rule' => array('between', 5, 15),
'required' => true,
'message' => 'Usernames must be between 5 to 15 characters'
),
'unique' => array(
'rule' => array('isUniqueUsername'),
'message' => 'This username is already in use'
)
)
);
为了示例
,我删除了第3条规则(字母/数字/短划线)接下来我的功能是检查我的数据库的用户名:
function isUniqueUsername($check) {
$username = $this->find(
'all',
array(
'fields' => array(
'User.id',
'User.username'
),
'conditions' => array(
'User.username' => $check['username']
)
)
);
if(!empty($username)){
if($this->data[$this->alias]['id'] == $username['']['id']){
return true;
}else{
return false;
}
}else{
return true;
}
}
这是"注册"
的控制器功能public function register() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been created'));
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('The user could not be created. Please, try again.'));
}
}
}
答案 0 :(得分:1)
更改
'unique' => array(
'rule' => array('isUniqueUsername'),
'message' => 'This username is already in use'
)
要
'unique' => array(
'rule' => 'isUnique',
'message' => 'This username is already in use'
)
你不需要那个功能来检查唯一性,Cake会用魔法为你做这件事。