Validate if value is true?


I have a table with payments. The user can insert certain amount of the payment in certain currency. Currencies are in related table, so every payment has CurrencyID (foreign key). I want to make sure that the user chooses from the Currencies dropdown a valid currency (he might try to submit malicious form with non-existing CurrencyID).

So my idea is to have a validator that checks if the CurrencyID submitted is existing and my idea is to do something like this (pseudo code):

return array(

array('CurrencyID', 'true', Currency::model()->findByAttributes(array('CurrencyID' => $this->CurrencyID)) instanceof CActiveRecord),


I can’t find a way to validate that the certain expression is true, the bool validator checks if value is eighter true or false (1 or 0).

How would you validate the above scenario, either with bool validator like I want or something completely different. I don’t know which is best practice.

Thank you!

Maybe an ‘exist’ validation rule could be of help (alias for CExistValidator)?

Ah well, no, I also though of a compare validator but what I actually forgot for a sec is that in all those cases, validators validate against the input value, not against an expression. So I did a custom validor:



 * CurrencyValidator validates that the currency exists in database



class CurrencyValidator extends CValidator



	 * Validates the attribute of the object.

	 * If there is any error, the error message is added to the object.

	 * @param CModel the object being validated

	 * @param string the attribute being validated


	protected function validateAttribute($object, $attribute)


		if (Currency::model()->findByAttributes(array('CurrencyID' => $object->CurrencyID)) instanceof CActiveRecord)

			return true;


		$message = $this->message !== null ? $this->message : Yii::t('general','Invalid {attribute}');

		$this->addError($object, $attribute, $message);



What do you mean with "validate against expression"? I still think CExistValidator would do what you want. Please also note its attributeName and className properties. You can even add your own conditions with criteria.

Ah, I’m sorry for not checking the exist validator in first place! This is exactly what I need and the best way to be done!!

Thank you Mike!

Btw, instead of having created an extension to CValidator, you could have just implemented a custom method within your model, and reference the name of your custom method as the 2nd parameter in your rule. That would make more sense, since you were building your validator extension to perform a specific query (which is logic specific to your model, whereas a validator class should be agnostic).