php Yii2:数组的验证规则?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27252934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yii2: validation rule for array?
提问by robsch
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 是一个整数数组?例如:
[['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.
更新:从 Yii 2.0.4 版开始,我们得到了一些帮助。看到这个答案。
回答by robsch
From version 2.0.4 there is the new EachValidatorwhich makes it more easy now:
从 2.0.4 版本开始,有新的EachValidator,现在它更容易:
['x', 'each', 'rule' => ['integer']],
This should be sufficient. If the values should be also checked you could use this (with the 'in' validatorwhich actually is the RangeValidator):
这应该足够了。如果还应该检查这些值,您可以使用它(使用实际上是 RangeValidator的“in”验证器):
['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:
但是,您也可以直接使用这个“in”验证器。这对于 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(). I'm not quite sure but I think those values are all sent as strings (like "5" instead of 5).
'strict' => true
如果数据由客户端发送并使用Model->load()设置,则使用可能没有意义。我不太确定,但我认为这些值都是作为字符串发送的(比如“5”而不是 5)。
回答by Ali MasudianPour
You may need to create custom validation rules like below:
您可能需要创建自定义验证规则,如下所示:
['x','checkIsArray']
Then in your model, impelement checkIsArray
:
然后在您的模型中, 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 emtementioned 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!');
}
}]
回答by Ekonoval
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] ]