Yii2 - 仅提交时的ajax验证,更改时的客户端验证

时间:2018-02-28 17:06:51

标签: yii yii2

是否可以在表单提交时启用ajax验证,并在更改/模糊时进行客户端/ JS验证?例如:

  1. 用户输入数据并按Tab键:客户端验证应适用
  2. 用户然后提交表单:应该应用ajax验证
  3. 如果验证成功,请继续使用普通表单提交
  4. 这是我的ActiveForm配置:

    <?php $form = ActiveForm::begin([
        'id' => 'login-form',
        'enableAjaxValidation' => true,
        'enableClientValidation' => true,
        'validateOnBlur' => true,
        'validateOnChange' => true,
        'validateOnSubmit' => true,
    ]); ?>
    

    目前,当我专注于一个字段时,它也将应用ajax验证 - 我不希望这样。

1 个答案:

答案 0 :(得分:1)

要按照您希望的方式工作,您需要通过AJAX提交表单,并且需要在afterValidate事件上附加处理程序。处理程序将替换默认表单提交,并负责将数据发送到服务器并在服务器验证失败时显示错误消息。显示验证消息需要在控制器端提供支持。

您可以分别在脚本中更新表单name/id。并在错误和不正确的服务器响应中添加警报。您的表单将通过ajax调用自动保存而无需重新加载您可以重置成功部分内的表单。

将处理程序附加到表单:

$this->registerJs('$(\'#my-form\').on(\'afterValidate\', function () {
    var $yiiform = $(this);
    $.ajax({
            type: $yiiform.attr(\'method\'),
            url: $yiiform.attr(\'action\'),
            data: $yiiform.serializeArray(),
        }
    )
        .done(function(data) {
            if(data.success) {
                $yiiform.submit();
                // data is saved
            } else if (data.validation) {
                // server validation failed
                $yiiform.yiiActiveForm(\'updateMessages\', data.validation, true); // renders validation messages at appropriate places
                console.log("error on form"+data.validation);
            } else {
                console.log("incorrect server response");
                // incorrect server response
            }
        })
        .fail(function () {
            console.log("request failed");
            // request failed
        })

    return false; // prevent default form submission
})');

请确保您的行动编码如下

<强> Controller action

public function actionUpdate($id)
{
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {

        //call model validate to trigger validation messages
        $model->validate();

        $result = [];

        // The code below comes from ActiveForm::validate(). We do not need to validate the model
        // again, as it was already validated by save(). Just collect the messages.
        foreach ($model->getErrors() as $attribute => $errors) {
            $result[\yii\helpers\Html::getInputId($model, $attribute)] = $errors;
        }
        if (!empty($result)) {
            return $this->asJson(['validation' => $result]);
        }

        return $this->asJson(['success' => true]);

    } elseif ($model->load(Yii::$app->request->post()) && $model->save()) {
        Yii::$app->session->setFlash('success', 'Form saved successfully');
        return $this->redirect('index');
    }

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

最重要的是,只需将enableClientValidation选项初始化为true,如下所示。

$form = ActiveForm::begin([
    'id' => 'login-form',
    'enableClientValidation' => true,
]);
相关问题