Validate dynamically filled array attribute on client-side

Hi everyone,

I’ve been searching and trying everything last couple of days with no result.

I have the following situation:

I am adding fields dynamically(with jQuery) on my page, with dynamically generated indexes:




name="B1[izhNo][0]"

name="B1[izhNo][1]"

name="B1[izhNo][3]"

name="B1[izhNo][8]"

...



The definition of the variable is:




public $izhNo;



and of course the name of the model is B1.

I am trying to validate all the dynamically added fields, but I don’t know what will be the count of those fields, that is why I make an array.

This is my rules method in the model B1:




public function rules()

{

   return array(

       array('izhNo','required'),

       array(),...

       array(),...

       ...

   );

}



I tried to make my custom client-side validator, like it’s posted in the Yii wiki

Implementing Client Validation ¶

but in the clientValidateAttribute method I could not get the $attribute parameter as an array of values and validate all the values…

When I create the rules method in this way:




public function rules()

{

   return array(

       array('izhNo[0]','required'),

       array(),...

       array(),...

       ...

   );

}



… I get the value, but it’s only the value of the field with name=“B1[izhNo][0]” and I need all the fields.

I am really stuck at this situation and I am not sure if I am missing something obviously or it couldn’t be done in this way?

Please somebody help with some recommendations and ideas.

Thanks in advance,

G.Velchev


public function rules(){   

	return array(   	

		array('izhNo','required'),      

		array('izhNo','myrule'),...   	

		array(),...   	...   

	);

}

public function myrule($attribute,$params){

	if(is_array($this->$attribute)){

		//any other validation

		}else{ 

			$this->addError($attribute, 'Not an array');

	}


}



Then you can create some action in your controller, send there ajax request, validate this request, and get response in ajax callback in case of error, and do the proper things on the client side if they are nescessary.