Yii Framework 2.0 $ model-> validate始终返回true

时间:2017-03-31 04:10:10

标签: php postgresql yii2

我是yii2框架的新手。我无法理解我在哪里犯了错误。这是我的代码。

public function rules()
    {
        return [
            // username and password are both required
            [['oldpassword', 'newpassword','reenternewpassword'], 'required'],
            // rememberMe must be a boolean value
            ['reenternewpassword', 'compare','compareAttribute'=>'newpassword'],
            // password is validated by validatePassword()
            ['oldpassword', 'validatePassword'],
        ];
    }

public function validatePassword()
    {

        $this->password_hash= User::findOne(['username'=>Yii::$app->user->identity->username,'status'=> User::STATUS_ACTIVE])->password_hash;
        if(is_null($this->oldpassword))
            return false;
        return Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash);
    }

型号:

public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validate()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}

这里validatePassword返回false但模型验证函数返回true。如何?请帮助我。

2 个答案:

答案 0 :(得分:1)

将函数public function validatePassword($attribute) { $this->password_hash= User::findOne([ 'username' => Yii::$app->user->identity->username, 'status'=> User::STATUS_ACTIVE ])->password_hash; if(is_null($this->oldpassword)) { $this->addError($attribute, \Yii::t('app', 'Wrong message'); } if(!Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash)) { $this->addError($attribute, \Yii::t('app', 'Wrong message'); } } 修改为:

keys = [(k,) * len(data[k]) for k in data.keys()]
data_vals = [data[k] for k in data.keys()]
output = [dict(kv) for kv in
          (zip(*pairs) for pairs in zip(zip(*keys), zip(*data_vals)))]

顺便说一下,你不检查User是否存在,这可能会在此验证器中抛出异常。

答案 1 :(得分:-1)

为什么不这样做,因为validatePassword()是检查值为true或false的方法,

public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validatePassword()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}