How to display validation error for a form field in Yii2?

0 like 0 dislike
6 views
How to display validation error for the old_password form in Yii2?
$this->addError() does not work.
public static function tableName() { return 'user'; } /** * @inheritdoc */ public function rules() { return [ [['first_name', 'last_name', 'email', 'repeat_password', 'old_password', 'new_password'], 'required'], [['is_admin'], 'integer'], [['created'], 'safe'], [['first_name', 'last_name', 'email', 'auth_key', 'token'], 'string', 'max' => 191], [['repeat_password', 'old_password', 'new_password'], 'string', 'max' => 191], ['old_password', 'validatePassword'], ['repeat_password', 'compare', 'compareAttribute' => 'new_password'], ]; } /** * @inheritdoc */ public function validatePassword() { if (!$this->hasErrors()) { $u = User::find()->where(['id' => Yii::$app->user->id])->one(); $user = $u->password; if (Yii::$app->getSecurity()->validatePassword($this->old_password, $user)) { var_dump('success'); }else{ $this->addError('old_password', 'Incorrect username or password.'); // var_dump('error'); } } }

and controller
$model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->validate()) { $model->password = \\Yii::$app->getSecurity()->generatePasswordHash($model->repeat_password); $model->save(); return $this->redirect(['view', 'id' => $model->id]); }
by | 6 views

2 Answers

0 like 0 dislike
In the model
['old_password', 'validatePassword','message' => 'some error'],
by
0 like 0 dislike
The fact that you have no client implementation validatePasword. Therefore, an error will be displayed only after loading the form and reload the page. I think it may help clientValidateAttribute method in the validators.
by

Related questions

0 like 0 dislike
1 answer
asked Jun 1, 2019 by DenisDangerous
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
0 like 0 dislike
2 answers
asked Apr 9, 2019 by Ghost2692
0 like 0 dislike
2 answers
110,608 questions
257,186 answers
0 comments
33,804 users