I have an form in which I am using Yii2 ajax
response to validate unique entities. Now, I have to add some custom jQuery validation and add Error Message and Error Class using jQuery
but as this field is not validated by Yii2 itself, ajax removes the error message and class which I added by jQuery. May someone help me to stop Yii2 ajax
to remove this custom validation.
I can't remove Yii2 Ajax because if I do so, it will not validate unique validation on blur.
here is some sample code.
from my _form.php
$('#w0').on('beforeSubmit', function (z) {
$(this).find('input.required').each(function () {
$(this).on('blur', function () {
if ($(this).val() == '') {
$(this).closest('div.form-group').addClass('has-error');
$(this).closest('div.form-group').find('p').html('This field can not be blank.');
return false;
}
});
});
});
Inside the controller, I have the following lines
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
This is contradictory, your JS event is called when submitted, but the inner line has blur
event, which will not happen. Because you are not moving from one field to another when you are submitting.
So it's not YII code, but it's your JS functions, which is wrong.
Give the following code a try, it should work:
$('#w0').on('beforeSubmit', function (z) {
$(this).find('input.required').each(function () {
if ($(this).val() == '') {
z.preventDefault();
$(this).closest('div.form-group').addClass('has-error');
$(this).closest('div.form-group').find('p').html('This field can not be blank.');
}
});
});