Validation of an unknown number of fields

Hello world !

I would like to use a rule and ActiveFields for validating a unknown number of fields (fields generated with a ‘for’ of ‘foreach’ loop) like in :


$count = count($model->foobar);

for ($i = 0;$i < $count;$i++) {

echo CHtml::activeTextField($model,'email');

}

I need to pass these fields to a validation rule but as I know a rule does have only a static name.

So, can you suggest something ?

you can specify a function name in the same class as validator, to which you can pass the entire array and do custom (or even built-in) validation on a per-item basis:




public function rules() {

  return array(

    array('attribute', 'customValidator'),

  );

}


...


public function customValidator($attribute, $params) {

  // Do your validation here, set errors on $this where appropriate

}



See also http://www.yiiframework.com/doc/guide/form.model#declaring-validation-rules

Ok but i can’t find somewhere the syntax for using the buit-in validation :


public function customValidator($attribute, $params) {

  foreach($this->foobar as $v) {

  if ($this->validate($v,'email')) {} // For the built-in email validator, Something like this <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' />?

  }

}

Just instantiate it as an object and call its validate() method, that should work. Haven’t tested it though. Check the class reference for CValidator or one of its subclasses, it’ll tell you how it works.

I think it is useful if Yii can handle multiple elements in an array directly, like this :


public function rules() {

  return array(

    array('foobar[*]', 'boolean'),

  );

}

Thanks Qiang for your quick reply @bug tracker, I found what I need, it is called :

Tabular Input