Dat Lam
Dat Lam

Reputation: 171

Yii2 ajax validation not work

I was trying to validate my YII2 register form but it not work. In view:

$form = ActiveForm::begin([
    'id'                   => 'register',
    'options'              => ['accept-charset'=>'utf-8'],
    'validateOnChange'     => false,
    'enableAjaxValidation' => true,
    'validateOnSubmit'     => true,
])

In controller:

$model = new MUser();

if($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax)
{
    $model->refresh();
    Yii::$app->response->format = 'json';
    return ActiveForm::validate($model);
}
elseif($model->load(Yii::$app->request->post()) && $model->save())
{
    \\do something
}

In Model:

public function rules()
{
    return [
               [
                   'username', 
                   'unique', 
                   'targetClass' => 'com\modules\admin\models\MUser',
                   'message'     => 'Username exist',
               ]
           ];
}

Can anyone let me know what wrong I am doing?

Upvotes: 3

Views: 4110

Answers (1)

aidonsnous
aidonsnous

Reputation: 1503

change

return ActiveForm::validate($model)

TO

 echo json_encode(ActiveForm::validate($model));
        \Yii::$app->end();

ActiveForm::validate($model) is an array it needs to be represented in json form which is done by json_encode and \Yii::$app->end(); is making sure that the application stop on just checking.Also make sure you have after the namespace :

use yii\web\Response;
use yii\widgets\ActiveForm;

But By doing so the submission via ajax of your form will not work the perfect way is using validationUrl.

Upvotes: 3

Related Questions