Yii2 – ActiveForm Ajax Validation and Submit

Some validations can only be done on the server-side, because only the server has the necessary information. For example, to validate if a username is unique or not, it is necessary to check the user table on the server-side. You can use AJAX-based validation in this case. It will trigger an AJAX request in the background to validate the input while keeping the same user experience as the regular client-side validation.

To enable AJAX validation for a single input field, configure the enableAjaxValidation property of that field to be true and specify a unique form id:



To enable AJAX validation for all inputs of the form, configure enableAjaxValidation to be true at the form level:



Note: When the enableAjaxValidation property is configured at both the input field level and the form level, the former will take precedence.


You also need to prepare the server so that it can handle the AJAX validation requests. This can be achieved by a code snippet like the following in the controller actions:



The above code will check whether the current request is an AJAX. If yes, it will respond to this request by running the validation and returning the errors in JSON format.


Info: You can also use Deferred Validation to perform AJAX validation. However, the AJAX validation feature described here is more systematic and requires less coding effort.


When both enableClientValidation and enableAjaxValidation are set to true, AJAX validation request will be triggered only after the successful client validation. Note that in case of validating a single field that happens if either validateOnChange, validateOnBlur or validateOnType is set to true, AJAX request will be sent when the field in question alone successfully passes client validation.



Prakash S

Prakash S

I would like to introduce myself as a Software professional opting for the career in software industry. I'm Prakash S, a MCA graduate and trained as industry level practice for Software technology. Basically I am a PHP Developer but now days exploring more in HTML5, CSS, AngularJS and jQuery libraries.