Yii Framework Forum: [Validator] Validate Attribute If Another Attribute Is Set - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

[Validator] Validate Attribute If Another Attribute Is Set Rate Topic: -----

#1 User is offline   rhomb 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 26
  • Joined: 28-September 11

Posted 26 November 2012 - 08:41 AM

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]'),
	[...]
)
}


1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users