我在afterValidate()事件中使用 ActiveForm ,但是目前afterValidate()在任何验证事件上都会触发。我如何区分事件validateOnSubmit,validateOnBlur和validateOnChange?
基本上,我只希望我的afterValidate()函数在提交时被触发。这是我的代码:
PHP:
<?php $form = ActiveForm::begin([
'id' => 'register-form',
'options' => [
'class' => 'validate-form',
],
'enableClientValidation' => true,
'enableAjaxValidation' => false,
'validateOnSubmit' => true,
'validateOnBlur' => true,
'validateOnChange' => true,
]); ?>
Run Code Online (Sandbox Code Playgroud)
JS:
// JS afterValidate function
$('.validate-form').on('afterValidate', function (event, messages, errorAttributes) {
$('.error-popup').show();
return false;
});
Run Code Online (Sandbox Code Playgroud)
HTML:
<div class="error-popup">Please review the errors in the form below.</div>
Run Code Online (Sandbox Code Playgroud)
正如您在我afterValidate()上面的函数中看到的那样,如果存在验证错误,则会显示一个错误弹出窗口。但是,如果用户提交表单时出现任何验证错误,我只希望此错误弹出窗口出现。
如果在模糊/更改时出现验证错误,则应该在没有任何错误弹出窗口的情况下进行正常的内联验证。
根据我的理解,beforeSubmit只有在验证通过时才会触发事件。
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();
}
});
Run Code Online (Sandbox Code Playgroud)