Unique yii2 validator only when the field is not empty

In Yii2, I have two fields in my database: emailandshopId

  • emailand shopIdshould be uniquetogether
  • emailcan also be empty( NULL), but is shopIdalways an integer

These are my rules in the model:

[['email'],'default','value' => NULL],
[['shopId'], 'integer'],
[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId'], 'message' => 'Already taken!'],

This does not work when I have two entries, for example. email="NULL"and shopId="1".

How can i solve this?

+4
source share
3 answers

Set the property skipOnEmptyat false http://www.yiiframework.com/doc-2.0/yii-validators-validator.html# $ skipOnEmpty-detail

+2
source

, .

[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId']]

email shopId, email ( ), shopId email, shopId (). DB.

, ,

[['email'], 'unique', 'targetAttribute' => ['email', 'shopId']]

: " email , , email shopId email.

+1

I used the when condition inside the rule

[
    ['email', 'shopId'],
    'unique',
    'targetAttribute' => ['email', 'shopId'],
    'message' => 'Diese E-Mail Adresse ist bereits registriert!',
    'when' => function ($model) {
        return !empty($model->email);
    }
],
0
source

Source: https://habr.com/ru/post/1678648/


All Articles