简体   繁体   English

Yii2:数组的验证规则?

[英]Yii2: validation rule for array?

I can define a rule for a single integer like this: 我可以为这样的单个整数定义规则:

[['x'], 'integer']

Is it possible to tell that x is an integer array? 有可能告诉x是整数数组吗? 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. 更新 :从Yii版本2.0.4我们得到了一些帮助。 See this answer . 看到这个答案

From version 2.0.4 there is the new EachValidator which makes it more easy now: 从版本2.0.4开始,新的EveryValidator使它现在更容易:

['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): 如果还应该检查这些值,你可以使用它(使用'in'验证器 ,它实际上是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. 但是,您也可以直接使用此“in”验证器。 And that is possible with Yii versions before 2.0.4: 对于2.0.4之前的Yii版本,这是可能的:

['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() . 如果数据由客户端发送并使用Model-> load()设置,则使用'strict' => true可能没有意义。 I'm not quite sure but I think those values are all sent as strings (like "5" instead of 5). 我不太确定,但我认为这些值都是以字符串形式发送的(比如“5”而不是5)。

You may need to create custom validation rules like below: 您可能需要创建如下的自定义验证规则:

['x','checkIsArray']

Then in your model, impelement checkIsArray : 然后在你的模型中, 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: 正如emte在评论中提到的那样,你也可以使用带有匿名函数的内联验证器,如下所示:

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

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] ]  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM