[Validator] Validate Attribute If Another Attribute Is Set

Hello folks,

even though it’s not put into a seperate class yet, I thought I drop this in here real quick. Might help someone to achieve this type of validation

validator:




public function validateOn($attribute,$params)

	{

		if (!isset($params['onAttribute']) || !isset($params['validator'])) 

			return;


		// default for set is true

		if (!isset($params['set'])) {

			$params['set'] = true;

		}


		// check for attributes to be set / not set

		$onAttributes = explode(',', $params['onAttribute']);

		foreach ($onAttributes as $attr) {

			if ($params['set'] && !$this->{trim($attr)}) 

				return;

			elseif(!$params['set'] && $this->{trim($attr)}) 

				return;

		}

	


		$rule = $params['validator'];


		unset($params['validator'], $params['set'], $params['onAttribute']);


		$validator = CValidator::createValidator($rule, $this, $attribute, $params);

		$validator->validate($this);

	}



Usage:




public function rules() {

return array(

	[...]

	array('[attribute_to_be_validated]', 'validateOn', 'validator' => 'required', 'onAttribute' =>   [attribute_dependend_on]'),

	[...]

)

}