1

When you are using Yii2's validation rules within a model, for example:

[['foo','bar'], 'integer],

Obviously ['foo','bar'] is an array, which I know you can use.

But can do pass a multi-dimensional array like this:

$this->numbers = [1,2,3];

[['foo','bar','numbers'], 'integer]

Will Yii2 accept this and check the correct data or will it test the value and return an error because numbers is an array?

3
  • Maybe this will help you, if you want to create a validation with certain allowed values. Do you mean foo and bar may only have value 1, 2 or 3? Commented Sep 27, 2015 at 17:49
  • Or numbers should be an integer array? Yes, that needs to be defined separately from foo and bar if these attributes are 'normal' integers. Commented Sep 27, 2015 at 18:00
  • @robsch Yep, the second one. I have moved them to using the each validator. Commented Sep 28, 2015 at 6:06

1 Answer 1

3

You need merge arrays for work rules

[ArrayHelper::merge(['foo','bar'], $this->getNumberFields()), 'integer']

Update:

Use each rule. See EachValidator.

public function rules()
{
    return [
        ['numbers', 'each', 'rule' => ['integer']],
    ]
}
Sign up to request clarification or add additional context in comments.

8 Comments

What is $this->getNumberFields()?
Function in your model that return field names array like ['dynamicIntegerFieldOne', 'integerFieldTwo'].
@Brett [ArrayHelper::merge(['foo','bar'], $this->numbers), 'integer'] could work. The rule will always be re-created when validation takes place. So $this->numbers can change from one to the next validation, if this is important.
@Brett Not sure what you mean. If you do the merge integer validations would be done for 5 attributes: foo, bar, dog, cat, fish. Those attributes should have integer values. They don't need to be explicitly declared, but they would be expected to exist when validation takes place. Isn't this what you wanted?
@brett Yii2 will get error. If rule integer, therefore numbers should be integer. You need each rule.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.