2016-11-07 29 views
0

有我的方式:Yii2誤差AJAX驗證運行JS腳本

$form = ActiveForm::begin([ 
     'id' => 'user-create-form', 
     'enableAjaxValidation' => true, 
     'enableClientValidation' => false, 
     'validationUrl' => Url::toRoute(Yii::$app->controller->id . '/validation'), 
     'validateOnType' => true, 
    ]); 

JS腳本註冊這個表格上,並根據對.keyup()事件的一些規則,以英語譯音進行俄語。音譯結果被添加到samname字段。

有一個在UserCreateForm模型驗證規則:

public function rules() 
    { 
     return [ 
     [['samname'], 'validateUserExist'], 
     ]; 
    } 

    public function validateUserExist() 
    { 
     $check = Yii::$app->CustomComponents->checkUserExist($this->samname); 
     if ($check) { 
      $errorMessage = 'User exists: ' . $check; 
      $this->addError('samname', $errorMessage); 
     } 
    } 

功能checkUserExist()檢查現有創建的名稱,並在匹配的情況下返回一個錯誤。

有行動上的控制器:

public function actionValidation() 
    { 
     $model = new UserCreateForm(); 

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

它的偉大工程,進行驗證,匹配的情況下返回一個錯誤......

但是!

需要再次運行JS腳本,並在錯誤時將下一個字母添加到名稱(JS腳本提供此功能)。如何在驗證器返回錯誤後再次運行JS腳本?

+0

我認爲它可以幫助你:https://yii2-cookbook.readthedocs.io/forms-activeform-js/ – yafater

+0

@yafater,我不明白是什麼事件是必要的使用和如何使用完全相同它。你幫我嗎? – rsnd

+0

我該怎麼幫你? – yafater

回答

0

@yafater感謝您的幫助!我找到解決辦法。

$('form').on('afterValidateAttribute', function (event, attribute, message) { 
     if (attribute.name === 'samname') 
     { 
      $.ajax({ 
       url: "url-to-action", 
       type: "POST", 
       dataType: "json", 
       data: $(this).serialize(), 
       success: function(response) { 
        if (typeof(response["form-samname"]) != "undefined" && response["form-samname"] !== null) { 
         // code here 
        } 
       }, 
      }); 
      return false; 
     } 
    }); 
+0

對不起,我很高興爲你解決。祝你好運。 – yafater