Checking for 'isUniqueUsername' in cakephp doesn't seem to work?

69 views Asked by At

I have a register form where when a user registers it asks for their Username, Password and email. For the username, I have a few rules such as:

  • Must be 5-12 characters
  • Must be unique
  • Must use only alpha, numbers, and dashes

With that being said, I can't seem to get my form to catch duplicate usernames, I was hoping someone could help me solve this!

Here is my User.php Model's Validate:

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'
            )
        )
);

I removed the 3rd rule (alpha/number/dash) for the sake of the example

Followed by my function to check my DB for the username:

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; 
}

}

here is the Controller function for "Register"

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.'));
            }   
        }
    }
1

There are 1 answers

4
IWillScoop On BEST ANSWER

Change

'unique' => array(
    'rule'    => array('isUniqueUsername'),
    'message' => 'This username is already in use'
 )

To

 'unique' => array(
     'rule' => 'isUnique',
     'message' => 'This username is already in use'
 )

You do not need that function to check for uniqueness, Cake does it for you with magic.