Rule for array field using Validators Each and Unique together


I’m using the Dynamic Model, and I’m trying to create a rule that combines the each with unique validator.

I did something like that but it did not work:

$this->addRule($attribute, ‘each’, [‘rule’ => [‘unique’]]);

I want no equal values in the $attribute, need validation like that:

$attribute = [1, 2]; //OK

$attribute = [1,1]; // NOT OK

Any suggestions?

Thank you for your time!


The unique validator is meant to validate that an entry in the database is unique.

In your case, you will probably want to create an inline validator which makes sure that array entries are unique.

Here’s an example implementation. You could tweak it to display the duplicates in the error message.

$this->addRule('my-attribute', function ($attribute, $params, $validator) {
    if (count(array_unique($this->$attribute)) !== count($this->$attribute)) {
          $this->addError($attribute, 'Duplicate values found');

Hi @machour

It works,

Thank you very much for the answer.


1 Like