Ajax Validation Only On Submit

I have been working on this problem for the last 2 days and I finally figured it out. I needed AJAX validation only when submitting a form and client side validation on each field change. From what I was able to figure out this combination is not supported by the CActiveForm object.

I wanted to share my solution since searching for this turned up nothing.

My CActiveForm config:

$form=$this->beginWidget ('CActiveForm', array (

 'id' => 'myform',

// 'enableAjaxValidation' => true, // Disabled to prevent ajax calls for every field update

 'enableClientValidation' => true,

 'clientOptions' => array(

  'validateOnSubmit' => true,

  'validateOnChange' => true, // allow client validation for every field



My ajaxSubmitButton config:

CHtml::ajaxSubmitButton ('Save', Yii::app()->request->url, array (

      'dataType' => 'json', // If this option is not set, the returned data is a string not a JSON object

      'success' =>

'js:function (data) {

 if (data) {



  $.each (settings.attributes, function (i) {

    $.fn.yiiactiveform.updateInput (settings.attributes[i], data, form);


 } else {

  alert (\'success\');



), array (

 'id' => 'myform_submit_'.rand(1,255), // Need a unique id or they start to conflict with more than one load.


I hope this helps someone out trying to figured out the same problem.

One thing to note, the $_POST[‘ajax’] var is not set by this method so you have to use the Yii::app()->request->isAjaxRequest to find out if this is a regular page load or a ajax request.

[color="#008000"]NOTE: moved to proper section (Tips, Snippets and Tutorials instead of General Discussion for Yii 1.1.x)[/color]

Nice tip ;)

Magister, welcome to the yii forum

cool … thanks

very nice tip. really needed to know how to validate form in JS with yii tools. Just a little remark. if(data) always returns true, so I use


I ended up with a very similar code. Just to contribute, I will add some more related tips:

  • You could add

$.fn.yiiactiveform.updateSummary(form, data);

after the loop where the updateInput calls are issued.

  • I also used


as phreak suggests.

  • In the controller you want to return: a) an empty object when the save action was successfull; b) the validation errors in the proper format otherwise. Here is my controller’s snippet:

$result = CActiveForm::validate($model);

if ($result == '[]') $this->saveModel($model);

echo $result;


Hope it helps. Cheers!