In the code below I’m working on a username validation.
I’d think that this would always throw an error, but it doesnt do anything.
How come it doesnt reach validateUsername() ?
class RegisterForm extends CFormModel
{
public $email;
public $username;
public $password;
public $password2;
private $_identity;
public function rules()
{
return array(
array('username', 'validateUsername'),
array('email, username, password, password2', 'required'),
array('password2', 'compare', 'compareAttribute' => 'password'),
);
}
public function validateUsername()
{
$this->addError('username','Username already exists.');
}
}
class RegisterForm extends CFormModel
{
public $email;
public $username;
public $password;
public $password2;
private $_identity;
public function rules()
{
return array(
array('username', 'validateUsername'),
array('email, username, password, password2', 'required'),
array('password2', 'compare', 'compareAttribute' => 'password'),
);
}
public function validateUsername($attribute,$params)
{ if(User::model()->exists('username=:username',array('username'=>$this->username))
$this->addError('username','Username already exists.');
}
}
2.Using CUniqueValidator
class RegisterForm extends CFormModel
{
public $email;
public $username;
public $password;
public $password2;
private $_identity;
public function rules()
{
return array(
array('username', 'unique','className'=>'User','attributeName'=>'username','message'=>"Username already exists"),
array('email, username, password, password2', 'required'),
array('password2', 'compare', 'compareAttribute' => 'password'),
);
}
}
Regards.
Note: Initially I have wrongly mentioned about the CExistValidator. Sorry for that.