Thursday 29 January 2015

Yii2: Validate unique if attribute is not empty

Yii2 unique validator, empty string and null is treated the same and ignored. It not the same as mysql when only null value ignored in unique check.
But this is not a bug, not all database management systemare the same with mysql.

So if you want to validate an attribute only when it not empty. Try the following rules :

['phone', 'filter', 'filter' => 'trim'], //trim string
['phone', 'default'], //set null if empty string
['phone', 'unique'],

Refer :