Answer the question
In order to leave comments, you need to log in
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' => 'Телефон занят'],
Answer the question
In order to leave comments, you need to log in
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, 'Телефон занят');
}
}
['phone', 'validatePhone'],
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question