Answer the question
In order to leave comments, you need to log in
[[+content_image]]
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' => [
User::STATUS_ACTIVE,
User::STATUS_NOT_ACTIVE,
]]
];
}
}
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){
if(Yii::$app->getUser()->login($user)){
return $this->goHome();
}
}
}else{
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">
<div>
<?= Html::submitButton('Зарегистрироваться', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
Answer the question
In order to leave comments, you need to log in
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]);
if($user){
$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');
For ajax validation to work, you need to enable it when displaying the form widget.
<?php
$form = ActiveForm::begin([
'id' => 'registration-form',
'enableAjaxValidation' => true,
])
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question