V
V
Vladislav2020-08-22 14:20:31
Yii
Vladislav, 2020-08-22 14:20:31

Why is the Yii2 validator not working?

Model: Setting

<?php

namespace app\modules\panel\models;

use app\models\User;
use Yii;
use yii\base\Model;

/**
 * Login the model behind the login form.
 */
class Setting extends Model
{
    public $login;
    public $name;
    public $vk;
    public $password;
    public $passwordTwo;

    public function rules()
    {
        return [
            [['login', 'name', 'vk'], 'string'],
            ['password', 'validatePassword'],
        ];
    }
    public function validatePassword($attribute, $params)
    {
        $this->addError($attribute, 'сразу ошибка без проверок');
    }
    
}

Action in controller:
public function actionSetting()
    {
        if (Yii::$app->request->isPost) {
            $model = new Setting();
            $model->load(Yii::$app->request->post());
            $model->updateUser();
        }
        $dbUser = User::findOne(Yii::$app->user->identity->id);
        $user = new Setting();
        $user->login = $dbUser->login;
        $user->name = $dbUser->name;
        $user->vk = $dbUser->vk;

        return $this->render('setting', compact('user'));
    }


Just for the sake of verification, I installed a built-in validator:
['passwordTwo', 'compare', 'compareAttribute' => 'password']

He works. But the custom one does not work ... It does not give anything at all. Not green nor red stroke:
K_gxEjtsQo.jpg

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
B
Bogdan Khvalko, 2020-08-24
@quitting

This $this->addError($attribute, 'immediate error without checks') will only work if the form is validated on the server. For dynamic validation, look for information in the docks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question