Yii2 - ActiveForm 和 afterValidate 事件

Yii2 - ActiveForm and afterValidate events

我将 ActiveForm 与 afterValidate() 事件一起使用,但是目前 afterValidate() 会在任何验证事件上触发。如何区分事件 validateOnSubmitvalidateOnBlurvalidateOnChange

基本上,我只希望我的 afterValidate() 函数在提交时被触发。这是我的代码:

PHP:

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

JS:

// JS afterValidate function
$('.validate-form').on('afterValidate', function (event, messages, errorAttributes) {
    $('.error-popup').show();

    return false;
});

HTML:

<div class="error-popup">Please review the errors in the form below.</div>

正如您在我上面的 afterValidate() 函数中看到的那样,如果存在验证错误,则会显示一个错误弹出窗口。但是,我只希望在用户提交表单时出现任何验证错误时出现此错误弹出窗口。

如果 blur/change 上存在验证错误,则正常的内联验证应该不会弹出任何错误。

据我了解,beforeSubmit 事件仅在验证通过时触发。

您可以通过以下方式解决此问题:

$("#register-form").on("beforeSubmit", function(event){
    $(this).yiiActiveForm('validateAttribute', 'contactform-phone');
    $(this).yiiActiveForm('validateAttribute', 'contactform-email');
    if ($(this).find('.has-error').length) {
        ...
    }
    ...
    return false;
});

提交按钮触发 beforeSubmit 事件,该事件反过来触发对您需要的任何字段的验证。如果验证结果错误,您可以执行与显示错误消息相关的 JS 逻辑。

Yii 的活动表单 JS 将一些信息保存到 yiiActiveForm 数据中 属性。您可以使用 submitting 属性 来确定表单在提交之前是否处于验证状态。

$('.validate-form').on('afterValidate', function (event, messages, errorAttributes) {
    let data = $('.validate-form').data('yiiActiveForm');
    //check if we are in submission process and if there are any errors
    if (data.submitting && errorAttributes.length > 0) {
        $('.error-popup').show();
    }
});

你应该在 afterValidate 之后发现 has-error class 并显示弹出窗口尝试下面的代码

$('.validate-form').on('afterValidate', function (event, messages, errorAttributes) {
        if ($('.validate-form').find('.has-error').length) {
            $('.error-popup').show();
        }
  });