Conditional Validation Rule

Hi!

I do want to add the following rule to my model:

if checkbox1 is checked, field2 and field3 are required

if checkbox4 is checked, field5 is required to be an e-mail address

How can I specify this? Problem seems to be that rules() is called too early, not just before validation, so I cannot dynamically concatenate the rules array.

I would write a validation method for field2 and field3 in the model class.




public function rules()

{

	return array(

		....

		array('field2, field3', 'validateF2andF3'),

		....

	);

}


public function validateF2andF3($attribute, $params)

{

	if ( $this->checkbox1 > 0 )

	{

		if ( $this->$attribute == '' )

		{

			$this->addError($attribute, 'Error message.');

		}

	}

}



Thanks. But can I use the build-in validators this way? (e.g. for the e-mail address)

Um, I haven’t done it myself yet, but looking it up in the reference of CEmailValidator, I think something like this should work.




public function rules()

{

        return array(

                ....

                array('field5', 'validateF5'),

                ....

        );

}


public function validateF5($attribute, $params)

{

        if ( $this->checkbox4 > 0 )

        {

                $ev = new CEmailValidator();

                $ev->allowEmpty = false;

                $ev->validate($this, $attribute);

        }

}



Please give it a try, and let me know if I’m wrong.

Thanks a lot! My solution is




public function validateF5($attribute, $params)

{

  if ($this->checkbox4) {

	$ev = new CEmailValidator();

	$ev->attributes = explode(',', $attribute);

	foreach ($params as $key=>$value)

      	$ev->$key = $value;

	$ev->validate($this);

  }

}



Even better:




public function validateF5($attribute, $params)

{

  if ($this->checkbox4) {

	$ev = CValidator::createValidator('required', $this, $attribute, $params);

	$ev->validate($this);

  }

}



Now there is an extension to do it:

Yii Conditional Validator

Posting for the case someone arrives here coming from a search page.

thanks for this good article