Using Unique Validator Standalone

Hi,

How do I use the UniqueValidator as a standalone object.

I want to validate an attribute in a model to make sure it is unique but I do not want to do it in the model.

How do I use this class to do it in the controller outside of the model?

James.

Not sure but have you tried




$validator = new \yii\validators\UniqueValidator();

if ($validator->validateAttribute($model, $attribute) { // set model instance and attribute to check

    // ok

} else {

    // error

}



validateAttribute returns void not boolean, so cannot be used.

Sorry, you are right.

But this should work:




$validator = new \yii\validators\UniqueValidator();

$validator->validateAttribute($model, $attribute);

if (empty($model->getErrors($attribute))) {

    // ok

} else {

    echo $model->getErrors($attribute);

}



Yes you are right, thanks.

I wonder why Yii just does not provide a solution for it though.