Validate form by ajax in yii2

Akhilesh Jha picture Akhilesh Jha · Nov 3, 2016 · Viewed 17.6k times · Source

I have a form which is opening in popup so I want to validate my form by ajax validation but when i click on submit button my page getting refreshed so I am not getting any validation error

View file:

 <?php $form = ActiveForm::begin([
        'id' => 'signup-form',
        'enableAjaxValidation' => true,
        //'action' => Url::toRoute('user/ajaxregistration'),
        'validationUrl' => Url::toRoute('user/ajaxregistration')

]); ?>

 <div class="col-md-12">
                    <div class="formbox">
                      <div class="inputbox signup">
                        <div class="input-group"> <span class="input-group-addon"><i class="glyphicon name"></i></span>
                          <?= Html::textInput('userFullName', '', ['placeholder' => "Name",'class'=>'form-control']); ?>
                        </div>

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

Controller File:

public function actionValidate() {

    $model = new SignupForm;

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model); \Yii::$app->end();

    }


}

Model Code:

 return [

            ['userFullName', 'trim'],
            ['userFullName', 'required'],


        ];

Please suggest me what should i do so that my page will not get refrsh and I will get the validation error

Answer

Dilworth picture Dilworth · Nov 11, 2016

You are using an ActiveForm without any ActiveFields, this means that the validation rules that have been defined within the model aren’t even being assigned to the text input. I have written an implementation for your problem:

Model:

use Yii;
use yii\base\Model;

class ExampleForm extends Model
{
    // this 'virtual attribute' defines a form field
    public $userFullName;

    // validation rules
    public function rules()
    {
        return [
            ['userFullName', 'trim'],
            ['userFullName', 'required'],
        ];
    }

}

Controller:

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

public function actionExample()
{
    $model = new ExampleForm;

    // validate any AJAX requests fired off by the form
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }

    if ($model->load(Yii::$app->request->post())) {

        // code to process form data goes here.. This will execute on a form submission.

    }

    return $this->render('example-form', [
        'model' => $model,
    ]);
}

View:

<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;

$this->title = 'Example';
?>
<div class="exampleForm">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>Please fill out the form.</p>

    <!-- this form will submit via POST to the same action that renders it -->
    <?php $form = ActiveForm::begin() ?>

        <!-- this is an active field. Any validation rules for the 'userFullName' field -->
        <!-- that have been defined within the $model object will be applied to this field -->
        <!-- the validation has also been set to validate via ajax within the $options array -->
        <!-- read more about ActiveFields here: http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html -->
        <?= $form->field($model, 'userFullName', ['enableAjaxValidation' => true]) ?>

        <div class="form-group">
            <?= Html::submitButton('Submit!', ['class' => 'btn btn-primary']) ?>
        </div>

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

</div>

The best way to see whether ajax requests are being sent off / the form is being validated is to check chromes developer tools, go to the network tab and inspect the activity.