V
V
Vladislav2020-02-15 11:09:44
Yii
Vladislav, 2020-02-15 11:09:44

Why are Yii2 validators not working?

There is a model for registration.

<?php 
namespace app\models;
use Yii;
use yii\base\Model;

class Registration extends Model{
  public $number;
  public $password;
  public $too_password;

  public function rules(){
    return [
      [['number', 'password', 'too_password'], 'required'],
      ['number', 'number'],
      [['password', 'too_password'], 'validatePassword'],
      ['number', 'validateNumber']
    ];
  }
  public function validatePassword($attribute, $params){
    if (mb_strlen($this->password) < 8)
    {
      $this->addError($attribute, 'Длина пароля должна быть более 8 символов');
    }
    if ($this->password != $this->too_password)
    {
      $this->addError($attribute, 'Пароли не совпадают');
    }
  }
  public function validateNumber($attribute, $params){
    die($this->number);
    if (mb_strlen($this->number) < 12)
    {
      $this->addError($attribute, 'Номер телефона начинается с +7 и состоит из 11 цифр включая цифру 7.');
    }
    if (mb_substr($this->number, 0, 2) != '+7')
    {
      $this->addError($attribute, 'Номер телефона должен начинаться с +7');
    }
  }
  public function attributeLabels()
    {
        return [
            'number' => Yii::t('app', 'Номер телефона'),
            'password' => Yii::t('app', 'Пароль'),
            'too_password' => Yii::t('app', 'Повторите пароль'),
            
        ];
    }
}

?>


Here is some action
public function actionRegistration(){

        $reg = new Registration();
        if(Yii::$app->request->post('Registration'))
        {
            if($reg->validate()){
                var_dump(Yii::$app->request->post('Registration'));die(); 
            }
           
            
        }

        return $this->render('registration', compact('reg'));
    }

Regardless of whether I enter everything correctly or not. I end up showing this picture
5e47a73ee8e79121143444.png
. Where are my mistakes? Which I added via $this->addError....
Help me figure it out, otherwise I don’t understand anything at all.
Where and what did I miss

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Dmitry Derepko, 2020-02-15
@cr1gger

Because you need to "load" the data.$reg->load(Yii::$app->request->post())

public function actionRegistration()
{
    $reg = new Registration();

    if($reg->load(Yii::$app->request->post()) && $reg->validate()) {
        exit('Валидация прошла!');
    }

    return $this->render('registration', ['reg' => $reg]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question