Answer the question
In order to leave comments, you need to log in
Ajax validation in Yii2. Why is a validation error not displayed for the uniqueness of the field?
Hello, I'm new to Yii2 and programming too. I am making a registration form, I need to check for the uniqueness of the email without reloading the page, I do this: view:
<?php $form = ActiveForm::begin(['id' => 'registration-form', 'enableAjaxValidation' => true]); ?>
<div class="form-group">
<label for="email-pop-up">E-mail</label>
<?= $form->field($model_reg, 'email')->textInput()->label(false); ?>
</div>
<div class="form-group">
<label for="password-pop-up-1">Пароль</label>
<?= yii\helpers\Html::activePasswordInput($model_reg, 'password', ['class' => 'form-control']); ?>
</div>
<div class="form-group">
<label for="password-pop-up-2">Повторить пароль</label>
<?= yii\helpers\Html::activePasswordInput($model_reg, 'password_repeat', ['class' => 'form-control']); ?>
</div>
public function rules(){
return [
[['email', 'password', 'password_repeat'],'required'],
['email', 'email'],
['email', 'unique', 'targetClass'=>'app\models\Person'],
['password', 'compare', 'compareAttribute' => 'password_repeat'],
];
}
$model_reg = new \app\models\Predreg();
if (Yii::$app->request->isAjax && $model_reg->load(Yii::$app->request->post('Predreg'))) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model_reg);
Yii::$app->end();
}
if (Yii::$app->request->post('Predreg')) {
$model_reg->attributes = Yii::$app->request->post('Predreg');
if ($model_reg->validate()){
if ($model_reg->predreg()){
return \yii\helpers\Url::home();
}
}
}
Answer the question
In order to leave comments, you need to log in
On the yiiframework.ru forum, they suggested that in order for the error to be displayed, you need to add validationUrl to the form
<?php $form = ActiveForm::begin([
'id' => 'registration-form',
'enableAjaxValidation' => true,
'validationUrl' => \yii\helpers\Url::to(['validate-form']), // Добавить URL валидации
]); ?>
public function actionValidateForm()
{
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new \app\models\Predreg();
if($model->load(Yii::$app->request->post()))
return \yii\widgets\ActiveForm::validate($model);
}
throw new \yii\web\BadRequestHttpException('Bad request!');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question