简体   繁体   English

在yii2中通过ajax验证表单

[英]Validate form by ajax in yii2

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 我有一个在弹出窗口中打开的表单,所以我想通过ajax验证来验证我的表单,但是当我单击“提交”按钮时,页面会刷新,因此我没有收到任何验证错误

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 请建议我该怎么做,这样我的页面将不会刷新,并且会收到验证错误

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. 您正在使用没有任何ActiveField的ActiveForm,这意味着在模型中定义的验证规则甚至都不会分配给文本输入。 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. 查看ajax请求是否已发送/表单正在验证的最好方法是检查chrome开发人员工具,转到“网络”标签,然后检查活动。

use renderAjax() Method: 使用renderAjax()方法:

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

 }else {
            return $this->renderAjax('YourViewFileName', [
                'model' => $model,
            ]);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM