I am using ActiveForm with the afterValidate()
event, however currently the afterValidate()
gets triggered on any validation event. How can I differentiate between the events validateOnSubmit
, validateOnBlur
and validateOnChange
?
Basically, I only want my afterValidate()
function to get triggered on submit. Here is my code:
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>
As you can see in my afterValidate()
function above, an error popup is shown if there are validation errors. However I only want this to error popup to appear if there are any validation errors when the user submits the form.
If there is a validation error on blur/change then the normal inline validation should occur without any error popup.
From my understanding, beforeSubmit
event is only triggered when validation has passed.
A form field is associated with a model and an attribute. It contains a label, an input and an error message and use them to interact with end users to collect their inputs for the attribute. See also $fieldConfig. The data model. The attribute name or expression. See yii\helpers\Html::getAttributeName () for the format about attribute expression.
When yii\base\Model::validate () is called, it will call two methods that you may override to customize the validation process: yii\base\Model::beforeValidate (): the default implementation will trigger a yii\base\Model::EVENT_BEFORE_VALIDATE event.
ActiveForm is a widget that builds an interactive HTML form for one or multiple data models. For more details and usage information on ActiveForm, see the guide article on forms.
To validate multiple models, simply pass each model as a parameter to this method, like the following: ActiveForm::validate ($model1, $model2, ...); The model to be validated. List of attributes that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated.
Yii's active form JS save some info into yiiActiveForm
data property. There is submitting
property that you can use to determine if the form is in validation before form submission.
$('.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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With