简体   繁体   English

Yii2 Ajax验证不起作用

[英]Yii2 ajax validation not work

I was trying to validate my YII2 register form but it not work. 我试图验证我的YII2注册表,但无法正常工作。 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? 谁能让我知道我在做什么错?

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() ; ActiveForm::validate($model)是一个数组,需要以json形式表示,该数组由json_encode和\\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. 但是这样做将无法通过表单的Ajax提交,这是使用validateUrl的理想方式。

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

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