Home > Net >  Yii2 apply validation rule on array of attributes
Yii2 apply validation rule on array of attributes

Time:01-20

I use Yii2 and model rules for validation.
I have an $id attribute which is an hash value. The validation rule looks like this:

 return [
            ['id', 'match', 'pattern' => '/^[a-f0-9]{16,32}$/i', 
                'on' => [self::SCENARIO_DEFAULT]],
            [...some more validation rules...]
  ]

This works fine with with $id = '17e94c10df492a39'

But now, I have an array of ids, like this:

$id_list = ['17e94c10df492a39','27e94c10df492a39','37e94c10df492a39'];

Is there a way to use the existing validator rule for this array? Or is there a way to define a new rule using the match-validator on an array?

I know, that it's possible to write an own validator. But it would be nice, if this works with yii2 on-board resources.

CodePudding user response:

What you are looking for is core validator each. This validator iterates through array and apply defined rule to each item in array. You can define the rule for example like this:

return [
   [
       'id_list',
       'each',
       'rule' => ['match', 'pattern' => '/^[a-f0-9]{16,32}$/i'],
    ],
    // ... other rules ...
];
  • Related