Yii2:数组的验证规则? [英] Yii2: validation rule for array?

查看:1102
本文介绍了Yii2:数组的验证规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以为单个整数定义规则,如下所示:

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

[['x'], 'integer']

是否可以判断x是整数数组?例如:

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?

更新:从Yii 2.0.4版开始,我们获得了一些帮助.参见此答案.

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

推荐答案

从2.0.4版开始,有一个新的EachValidator ,现在可以更轻松地进行此操作:

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

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

这应该足够了.如果还应该检查值,则可以使用此值(与"in"验证器实际上是RangeValidator):

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

但是,您也可以直接使用此"in"验证器.对于2.0.4之前的Yii版本,这是可能的:

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).

这篇关于Yii2:数组的验证规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆