D
D
dev4002016-11-22 15:32:48
Yii
dev400, 2016-11-22 15:32:48

How to properly validate a unique field?

I'm trying to make the phone unique, following the example of other validation rules

['phone', 'trim'],
            ['phone_repeat', 'trim'],
            ['phone', 'required'],
            ['phone_repeat', 'required'],
            ['phone', 'string', 'min' => 10],
            ['phone_repeat', 'compare', 'compareAttribute' => 'phone'],
            ['phone', 'unique', 'targetClass' => '\app\models\User', 'message' => 'Телефон занят'],

But when I try to record a phone that is already in the database, I get an exception ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
davidnum95, 2016-11-22
@dev400

You can write your own validator. Something like:

public function validatePhone($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = User::findOne(['phone' => $this->$attribute]);

            if ($user ) {
                $this->addError($attribute, 'Телефон занят');
        }
    }

In rules:
['phone', 'validatePhone'],

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question