Answer the question
In order to leave comments, you need to log in
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', 'Повторите пароль'),
];
}
}
?>
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'));
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question