Barkasth2015-10-14 14:01:29
Barkasth, 2015-10-14 14:01:29

AJAX check for uniqueness of YII2 username does not work. Can you tell me what's wrong in the code?

Model rules:

public function rules()
        return [
            [['username', 'password_hash', 'status'], 'required'],
            ['username', 'unique'],
            ['password_hash', 'string', 'min' => 6, 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            ['status', 'in','range' => [

controller action
public function actionReg()
        $model = new RegForm();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = 'json';
            return \yii\widgets\ActiveForm::validate($model);
        if($model->load(Yii::$app->request->post()) && $model->validate()){
            if($user = $model->reg()){
                if($user->status === User::STATUS_ACTIVE){
                        return $this->goHome();
                echo '<pre>';
                Yii::$app->session->setFlash('error','Возникла ошибка при регистрации');
                Yii::error('Возникла ошибка при регистрации');
                return $this->refresh();
        return $this->render('reg',
            ['model' => $model]

<?php $form = ActiveForm::begin(['id' => 'registration-form',])?>

        <?= $form->field($model, 'username',['enableAjaxValidation' => true]) ?>

        <?= $form->field($model, 'password_hash')->passwordInput() ?>
        <?= $form->field($model, 'password_repeat')->passwordInput() ?>
        <?= $form->field($model, 'status')->hiddenInput()?>

        <div class="form-group">
                <?= Html::submitButton('Зарегистрироваться', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>

    <?php ActiveForm::end(); ?>

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
Barkasth, 2015-10-14

no, that's not the point... we set it to only one field, and if we add it to the widget, then the whole field, but it doesn't work either...
figured out: ['username', 'unique'] - it works only with ActiveRecord attributes. And I have class RegForm extends Model.
Changed: ['username', 'ajaxValidate'],
public function ajaxValidate($attribute)
$user = User::findOne(['username' => $this->username]);
$this->addError($attribute, 'User with such login exists');
}elseif (!preg_match('/\+\d{12,15}/', $this->username)) {
$this->addError($attribute, 'Enter your phone number in the format +111111111111');

Maxim Timofeev, 2015-10-14

For ajax validation to work, you need to enable it when displaying the form widget.

$form = ActiveForm::begin([
'id' => 'registration-form',
'enableAjaxValidation' => true,

You should also check the url where the form is sent and it is possible to specify it explicitly in the widget config. I will add that you can specify not only the send url, but also the url for ajax validation, they can be different actions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question