Validate the sum of two model attributes

Hi guys,

I am kinda new to Yii, but so far I like it very much. Nevertheless I am not quite sure what is the best solution for this problem:

Assume i have a model called Foo. Foo has two attributes ‘bar1’ and ‘bar2’. Both attributes can be set by a user in a corresponding view. The tricky part is I want to validate if the sum of bar1 and bar2 is equal to five (bar1 + bar2= 5).




 property integer $bar1

 property integer $bar2

 property integer $bar3

 property integer $bar4

class Foo extends \yii\db\ActiveRecord {

  //TODO: Define a rule to ensure bar1 + bar1 = 5 and bar3 + bar4 = 5 and so on...

}



In an ideal case I would like to define a rule that checks for the constraint and returns an error message if this is not fulfilled. In some threads I read about beforeValidate() and afterValidate() functions. The problem with that is I got a lot of other fields e.g bar3 and bar4 for which the same pattern applies. So I want to return a specific error message and not just a random message like "Validation failed".

Best regards