1
votes

I am trying to make this custom validation works, but I am not getting anything at the moment. What seems to be the problem?

['password', function($attribute, $params){

                $password = \Yii::$app->db
                    ->createCommand("SELECT * FROM forbiddenPasswords WHERE password = '{$params}'")
                    ->queryOne();

                if($password)
                    $this->addError($attribute, 'This password is forbidden. Please try another.');
            }],
3

3 Answers

3
votes
  • $params contains validator parameters, not attribute,
  • you should correctly bind parameter in your query.

e.g. :

$count = Yii::$app->db->createCommand('SELECT COUNT(*) FROM forbiddenPasswords WHERE password = :password')
    ->bindValue(':password', $this->password)
    ->queryScalar();

if($count)
    $this->addError($attribute, 'This password is forbidden. Please try another.');

Or you could create an ActiveRecord model for forbiddenPasswords and use unique validator to do the same...

0
votes

I have checked that {$params} variable is for additional values. And if you want to validate password assign the value like this.

 ['password', function($attribute, $params){

           $pass=$this->password;
            $password = \Yii::$app->db
                ->createCommand("SELECT * FROM forbiddenPasswords WHERE password = '{$pass}'")
                ->queryOne();

            if($password)
                $this->addError($attribute, 'This password is forbidden. Please try another.');
        }],
0
votes

Don't write open password validator. It's unsecure!

In Yii2 you can use validatePassword method of Security component.

First store in database hash of password by setPassword method:

/**
 *
 * @param string $password WARNING! OPEN PASSWORD!
 */
public function setPassword($password)
{
    $this->password_hash = Yii::$app->security->generatePasswordHash($password);
}

In model you should have method validatePassword:

/**
 * @param string $password WARNING! OPEN PASSWORD!
 *
 * @return boolean
 */
public function validatePassword($password)
{
    return Yii::$app->security->validatePassword($password, $this->password_hash);
}

Or, if you want use User model as form you can write this:

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        ...
        ['password', 'validatePassword']
    ];
}

/**
 * @param string $attribute attribute name
 * @param array $params Additional params
 */
public function validatePassword($attribute, $params)
{
    if (Yii::$app->security->validatePassword($this->$attribute, $this->password_hash) == false) {
        $this->addError($attribute, Yii::t('frontend', 'Incorrect password'));
    }
}