There is a form:

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

A js-script is connected to the form, which performs the transliteration of Russian letters, according to the rule, when typing them in the appropriate fields (event .keyup() ) and adds the result to the samname field.

There is a validation rule in the UserCreateForm model:

 public function rules() { return [ [['samname'], 'validateUserExist'], ]; } public function validateUserExist() { $check = Yii::$app->CustomComponents->checkUserExist($this->samname); if ($check) { $errorMessage = 'Найден: ' . $check; $this->addError('samname', $errorMessage); } } 

The checkUserExist() function checks the existence of the created name and returns a result if found.

And action in the controller:

 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(); } } 

And everything works fine - validation is performed, and an error is returned if the name is found.

But!

It is necessary for me that when the error returns, the script is executed again and add another letter to the name (this functionality is included in it). How can this be implemented?

How to run the script when the error is returned by the validator and run the check again?

    1 answer 1

    Solution: use the 'afterValidateAttribute' event.

      $('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; } }); 

    Source: https://yii2-cookbook.readthedocs.io/forms-activeform-js/