Yii2: validation rule for array?

53,790

Solution 1

From version 2.0.4 there is the new EachValidator which makes it more easy now:

['x', 'each', 'rule' => ['integer']],

This should be sufficient. If the values should be also checked you could use this (with the 'in' validator which actually is the RangeValidator):

['x', 'each', 'rule' => ['in', 'range' => [2, 4, 6, 8]]], // each value in x can only be 2, 4, 6 or 8

However, you can use this 'in' validator also directly. And that is possible with Yii versions before 2.0.4:

['x', 'in', 'range' => [2, 4, 6, 8], 'allowArray' => true]

The use of 'strict' => true would probably makes no sense in case the data is sent by the client and is set with Model->load(). I'm not quite sure but I think those values are all sent as strings (like "5" instead of 5).

Solution 2

You may need to create custom validation rules like below:

['x','checkIsArray']

Then in your model, impelement checkIsArray:

public function checkIsArray(){
     if(!is_array($this->x)){
         $this->addError('x','X is not array!');
     }
}

You can do all you need into a custom validation rule.


As emte mentioned on comment, you can also use inline validator with anonymous function like below:

['x',function ($attribute, $params) {
    if(!is_array($this->x)){
         $this->addError('x','X is not array!');
     }
}]

Solution 3

If you need to check against specific range for each array element

['x', 'required'] 

plus

['x', 'each', 'rule' => ['in',  'allowArray' => true, 'range' => [2, 4, 6, 8]]]

or

['x', 'in', 'allowArray' => true,  'range' => [2, 4, 6, 8] ]  
Share:
53,790
robsch
Author by

robsch

Peace for Urkaine! Putin's war is the biggest desaster since the last world war. Russion people: Face it! Think about why almost the whole world has a problem with you. That cannot be fake. Protest against Putin's regime, ASAP!!! Software developer in Austria. Loving the idea of StackExchange.

Updated on August 03, 2022

Comments

  • robsch
    robsch almost 2 years

    I can define a rule for a single integer like this:

    [['x'], 'integer']
    

    Is it possible to tell that x is an integer array? For example:

    [['x'], 'integer[]']
    

    And could I specify the valid values in the array?

    Update: From Yii version 2.0.4 we've got some help. See this answer.