Problem with unique validator

I’m not sure if I’m doing something wrong, but there seems to be a problem with unique validator.

I have a simple rule:


[['a1'], 'unique', 'targetAttribute' => ['a1','a2','a3']

I’m getting some strange results:


$model->validate()      	->> true


$model->save()   			->> true

If ran separately, it even saves the data to the db. BUT, when I run validate() first and then try to save(), it gives me false and the correct error message without saving to the database. What is going on? I’m not encountering any problems with other validators (string, required etc.)


$model->validate();$model->save(); -->> false and prevents saving to the db

Hi walther,

You are not checking the return value of validate().

Is it exactly what you have in your code?

The code is a little bit more complicated of course, I’m checking the value in the “if” condition, though I tried to check its value by dumping and echoing it as well. Same result. If I run save() without running validate() first, it saves to the database in spite of wrong data, as if the validator never runs. When I run validate() first, suddenly save() returns the error (not the validate() though). I’m not overloading the validate or save methods at all, so I’m really puzzled what’s happening here.

I’ll probably try to create an isolated test project to see if it behaves the same way (and post here as an executable example for others to test) when I have more time, but in the meantime I’d like to know if someone else encountered such weird problem.

I think I would try the syntax in the last example

https://www.yiiframework.com/doc/api/2.0/yii-validators-uniquevalidator

I see.

Yeah, I want to see it.

BTW, frankly saying I don’t like the complicated syntax of the unique validator. I couldn’t get a clear understanding what it is supposed to do after reading the document several times. :(

Just guessing here …

Probably the attribute to validate and the first targetAttribute form an implicit pair for comparison (a1, a2).

Additional targetAttributes need to be pairs (e.g. a1, a3).

Sort of makes sense …

https://www.yiiframework.com/doc/api/2.0/yii-validators-uniquevalidator#$targetAttribute-detail